我是使用 JSON 的新手,我想知道是否有更好的方法来完成我在下面的代码中所做的事情。您会注意到,要访问嵌套的 JSON 对象,我必须先创建子 JSON 对象/数组,然后才能访问 JSON 数组元素“leagues”。有没有更快或更简单的方法来做到这一点?
public static void main( String[] args ) throws UnirestException
{
JsonNode response = Unirest.get("http://www.api-football.com/demo/api/v2/leagues")
.header("x-rapidapi-host", "api-football-v1.p.rapidapi.com")
.header("x-rapidapi-key", "")
.asJson()
.getBody();
JSONObject json = new JSONObject( response );
JSONArray jArray = json.getJSONArray( "array" );
JSONObject jAPI = jArray.getJSONObject(0);
JSONObject jLeagues = jAPI.getJSONObject( "api" );
JSONArray jArrayLeagues = jLeagues.getJSONArray( "leagues" );
for(int n = 0; n < jArrayLeagues.length(); n++) {
JSONObject leagues = jArrayLeagues.getJSONObject(n);
System.out.print(leagues.getString("name") + " " );
System.out.print(leagues.getString("country") + " ");
System.out.println( leagues.getInt("league_id") + " " );
}
}
慕虎7371278
相关分类