Capturing field of a complex JSON

0

I'm using the Java language, with the org.json version 2017101 library to capture data from a JSON. Follow JSON below:

{query:

{"UF":"SP", "results":

{"cidades":[

{"cidade":"sao paulo", "contagem":564561}, {"cidade":"rebeirao","contagem":5212884}]}}}

To get only the internal JSON "cities", which is what I would need in my application, I did as follows:

        String jsonString = IOUtils.toString(url);

        JSONObject generateJson = new JSONObject(jsonString);
        JSONObject generateJson2 = generateJson.getJSONObject("query");
        JSONObject generateJson3 = generateJson2.getJSONObject("results");

        JSONArray jsonRates = generateJson3.getJSONArray("cidades");

I found the code to be somewhat "gambiarra", is there another way to get only the "cities" array?

    
asked by anonymous 30.10.2017 / 14:37

1 answer

0

I think the simplest way using JSONArray is like this:

JSONArray jsonRates = new JSONObject(jsonString)
  .getJSONObject("query")
  .getJSONObject("results")
  .getJSONArray("cidades");
    
30.10.2017 / 14:50