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();
}
}
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
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];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.