Capture field of a complex JSON

Asked

Viewed 220 times

0

I am 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 it 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 thought the code was half "gambiarra", there is another way to get only the "cities" array"?

1 answer

0


I believe the simplest way using JSONArray that’s how it is:

JSONArray jsonRates = new JSONObject(jsonString)
  .getJSONObject("query")
  .getJSONObject("results")
  .getJSONArray("cidades");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.