0

Hello I'm new to android studio and I'm currently trying to figure out how to parse this json file: http://stman1.cs.unh.edu:6191/games into a 2d array. I can't seem to figure out a simple way of doing this.

I'm not sure exactly why object types are returned by the JsonObject. I know it can't be converted to an int because it's likely an array of ints but I also can't get that array because it doesn't have a name like the outer array.

public void onResponse(JSONObject response) {
   try {
      JSONArray jsonArray = response.getJSONArray("grid");

      for( int i=0; i < jsonArray.length(); i++ ){
          JSONObject num = jsonArray.getJSONObject(i);
          gridVals[i] = num.getInt();
      }

   } catch (JSONException e) {
      e.printStackTrace();
   }
}
2
  • please prefer using library like Gson, it will save you a lot of time in future. I have few example here, please give it a try stackoverflow.com/search?q=user:4192693+[json] Commented Sep 13, 2019 at 4:31
  • Yeah, the built-in JSON objects don't handle 2D arrays very well. Commented Sep 13, 2019 at 4:42

2 Answers 2

2

Here is a simple example which you can use directly if you are using Gson library.

class Response{

    List<List<Integer>> grid= new ArrayList<>();
}

public class ParsingJson {

    public static void main(String[] args) {
        // data is your json string that you need to provide here 
        Response response = (new Gson()).fromJson(data, Response.class);

        System.out.println(response.grid.size());

        for (List<Integer> integers : response.grid) {
            for (Integer integer : integers) {
                System.out.println(integer);
            }
        }

    }

}

I have tried reading your json data using Gson library

Sign up to request clarification or add additional context in comments.

Comments

1

You need two for loops for 2d array

for (int i = 0; i < jsonArray.length(); i++) {
    JSONArray internaljsonArray = jsonArray.getJSONArray(i);
    for (int j = 0; j < internaljsonArray.length(); j++) {

        JSONObject num = internaljsonArray.getJSONObject(j);
        gridVals[i][j] = Integer.getInteger(num.toString());
    }
}

And gridVals should be declared at least as

Integer gridVals[][]=new Integer[100][100];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.