How to get the string of a parent Json or a Json in array format?

Asked

Viewed 603 times

4

I got the following JSON:

String json = "{\n" +
            "\n" +
            "    \"Pessoas\":[\n" +
            "        {\n" +
            "            \"NomeHomem\":{\n" +
            "                \"Idade\":1\n" +
            "            }\n" +
            "        },\n" +
            "        {\n" +
            "            \"NomeMulher\":{\n" +
            "                \"Idade\":true\n" +
            "            }\n" +
            "        },\n" +
            "        {\n" +
            "            \"NomeCrianca\":{\n" +
            "                \"Idade\":\"string\"\n" +
            "            }\n" +
            "        }\n" +
            "    ]\n" +
            "\n" +
            "}";

When there is no array like this I use one getString("Pessoas"); and it works. But in this case, how to do?

1 answer

0


Considering your JSON, below:

{
   "Pessoas":[
      {
         "NomeHomem":{
            "Idade":1
         }
      },
      {
         "NomeMulher":{
            "Idade":true
         }
      },
      {
         "NomeCrianca":{
            "Idade":"string"
         }
      }
   ]
}

As you well noted now we have a array of people. In this case we must recover as a JSONArray and recover each element, which there will be a Pessoa and then get your values back, something like that:

final JSONObject json = new JSONObject(json);
final JSONArray pessoas = json.getJSONArray("Pessoas");
final int pSize = pessoas.length();
for (int i = 0; i < pSize; i++) {
    final JSONObject pessoa = pessoas.getJSONObject(i);
    System.out.println(pessoa);
}

In this case the result obtained will be this:

{"NomeHomem":{"Idade":1}}
{"NomeMulher":{"Idade":true}}
{"NomeCrianca":{"Idade":"string"}}

EDITION

If you also want the string that represents People you can call the toString of JSONArray, in this way:

pessoas.toString();

Or so, it will format the output:

pessoas.toString(2);

The first way will generate this result:

[{"NomeHomem":{"Idade":1}},{"NomeMulher":{"Idade":true}},{"NomeCrianca":{"Idade":"string"}}]

And the second this:

[
  {"NomeHomem": {"Idade": 1}},
  {"NomeMulher": {"Idade": true}},
  {"NomeCrianca": {"Idade": "string"}}
]
  • Thanks, but is there any way to get the string "people"? I needed to use it too.

  • @daniel12345smith updated the answer, see if this is what you need. If not, update your question with the expected result.

  • Valew Bruno, with this I can already manage here.

Browser other questions tagged

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