Iteración de matriz JSON en Android / Java


Estoy construyendo una aplicación para Android que necesita descargarse y sincronizarse con una base de datos en línea, estoy enviando mi consulta desde la aplicación a una página php que devuelve las filas relevantes de una base de datos en formato JSON.

¿Puede alguien por favor decirme la mejor manera de iterar a través de una matriz JSON?

Recibo una matriz de objetos:

[{json object},{json object},{json object}]

¿Cuál es la pieza de código más simple que podría usar para acceder a los JSONObjects en el array?

EDITAR: ahora que lo pienso el método que utilicé para iterar el bucle fue:

for (String row: json){
     id = row.getInt("id");
     name = row.getString("name");
     password = row.getString("password");
}

Así que supongo que tenía fue de alguna manera capaz de convertir el Json devuelto en una matriz iterable. ¿Alguna idea de cómo podría lograr esto?

Me disculpo por mi vaguness pero tenía esto trabajando a partir de un ejemplo que encontré en la web y desde entonces no he podido encontrarlo.

Author: Svetoslav Marinov, 2010-08-04

8 answers

Lo he hecho de dos maneras diferentes,

1.) hacer un Mapa

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i=0; i<settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) hacer un JSONArray de nombres

    JSONArray names = json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i=0; i<values.length(); i++){
        if (names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if (names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if (names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if (names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if (names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if (names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }
 66
Author: schwiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 21:46:55

Creo que este código es corto y claro:

int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    id = row.getInt("id");
    name = row.getString("name");
}

¿Es eso lo que estabas buscando?

 316
Author: vipw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-05 10:29:01

Desafortunadamente, JSONArray no admite cada instrucción, como:

for(JSONObject someObj : someJsonArray) {
    // do something about someObj
    ....
    ....
}
 4
Author: Dream,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 08:14:09

Si está utilizando el JSON.org Java implementation , que es de código abierto, solo puede hacer que JSONArray implemente la interfaz Iterable y agregue el siguiente método a la clase:

@Override
public Iterator iterator() {
    return this.myArrayList.iterator();
}

Esto hará que todas las instancias de JSONArray sean iterables, lo que significa que la sintaxis for (Object foo : bar) ahora funcionará con ella (tenga en cuenta que foo tiene que ser un Objeto, porque JSONArrays no tiene un tipo declarado). Todo esto funciona porque la clase JSONArray está respaldada por una sencilla ArrayList, que ya iterable. Imagino que otras implementaciones de código abierto serían igual de fáciles de cambiar.

 3
Author: Thunderforge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-14 02:22:58

En matrices, busque:

JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 
 3
Author: Paul Burke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 08:22:58

Está utilizando el mismo objeto Cast para cada entrada. En cada iteración simplemente cambiaste el mismo objeto en lugar de crear uno nuevo.

Este código debería arreglarlo:

JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();

for (int i=0; i < jCastArr.length(); i++) {
    Cast person = new Cast();  // create a new object here
    JSONObject jpersonObj = jCastArr.getJSONObject(i);

    person.castId = (String) jpersonObj.getString("id");
    person.castFullName = (String) jpersonObj.getString("name");

    castList.add(person);
}
details.castList = castList;
 2
Author: Andriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-08 11:29:17

Cuando probé la sugerencia de @vipw, me enfrenté a esta excepción: The method getJSONObject(int) is undefined for the type JSONArray

Esto funcionó para mí en su lugar:

int myJsonArraySize = myJsonArray.size();

for (int i = 0; i < myJsonArraySize; i++) {
    JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);

    // Do whatever you have to do to myJsonObject...
}
 2
Author: Graham S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-30 03:01:39

Mientras se itera sobre una matriz JSON (org.json.JSONArray, integrado en Android), tenga cuidado con los objetos null; por ejemplo, puede obtener "null" en lugar de una cadena null.

Un cheque puede verse como:

s[i] = array.isNull(i) ? null : array.getString(i);
 1
Author: 18446744073709551615,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 08:02:32