Extracting data from JSON array

Here is the idea :

JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");

// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);

// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");

// and so on, you can process leaguesArray similarly

It should work (feel free to complain about compile errors if there are any)


Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):

String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));

I might have used another JSON library than you.

Tags:

Java

Json