Tour Json Array of 4 levels or more Java (android)

0

I have a JSON that has 4 JSON objects, my question is how to travel in such a way that with first do one thing with the second one and so on I've tried with:

JSONArray ja = new JSONArray(response);
  for (int i = 0; i < ja.length(); i++) {                                   
    JSONObject row = ja.getJSONObject(i);
    String pasi =row.getString("nombre");
    }

But only melo goes through if it receives a JSON object, the problem is that it must receive one of 4 levels (4 arrays within a single one)

The received json is the following:

{"paises":[{"id":"68","nombre":"El Salvador","activo":"1"},{"id":"70","nombre":"Eritrea","activo":"0"}],

"procedencia":[{"id":"1","nombre":"Establecimiento"},{"id":"2","nombre":"Colvol"},{"id":"3","nombre":"Promotor Antimalaria"}],

"clave":[{"id":"2","id_departamento":"11","id_municipio":"185","correlativo":"40","clave":"11-40"}],

"departamento":[{"id":"1","nombre":"Ahuachap\u00e1n","id_pais":"68"},{"id":"2","nombre":"Santa Ana","id_pais":"68"}]}
    
asked by Igmer Rodriguez 21.08.2018 в 23:47
source

1 answer

1

What I understand is that you want to access all the values within any of the Arrays.

To answer your question I will use one of the arrays. In this case, that of countries. Let's say I want to get the name of the second object, "Eritrea."

In this case first of all you must have a JsonObject that contains all your JSON, that is to say your 4 arrays. Once you have done that you must create a JsonArray. As I am going to access the information of the Array of countries, I will do the following:

JsonObject tuJson; //Ya debe estar inicializado
JsonArray paises = tuJson.getJsonArray("paises"); 

Once this is done, the JsonArray of countries contains the following:

{"paises":[{"id":"68","nombre":"El Salvador","activo":"1"},{"id":"70","nombre":"Eritrea","activo":"0"}]

And from now on it works like any Array. The index 0 would be the first object, that is to say the object that has as "id" 68 and as "name" El salvador. I said I wanted to access the second object and get its name "Eritrea", so I do the following:

JsonObject segundo = paises.getJsonObject(1); //Segundo objeto, index 1
String nombre = segundo.getString("nombre"); //Nombre tendra como valor "Eritrea"

You said you wanted to go through everything so it would look something like this:

for(int x = 0; x < paises.size(); x++){
   JsonObject elemento = paises.getJsonObject(x);
   int id = elemento.getInt("id");
   String nombre = elemento.getString("nombre");
}

I hope it will be helpful and forgive me if you misunderstand your question, I can not comment to ask for clarification. The process is basically the same for the 4 arrays.

    
answered by 22.08.2018 / 01:41
source