Acceso a miembros de elementos en un JSONArray con Java


Acabo de empezar a usar json con java. No estoy seguro de cómo acceder a los valores de cadena dentro de un JSONArray. Por ejemplo, mi json se ve así:

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}

Mi código:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

Tengo acceso al JSONArray "record" en este punto, pero no estoy seguro de cómo obtendría los valores "id" y "loc" dentro de un bucle for. Lo siento si esta descripción no es demasiado clara, soy un poco nuevo en la programación.

Author: Michael A. Jackson, 2009-10-15

6 answers

¿Ha intentado usar [JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject (int)), y [JSONArray.length()](http://json.org/javadoc/org/json/JSONArray.html#length ()) para crear tu bucle for:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}
 187
Author: notnoop,
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
2009-10-14 20:32:32

An org.json.JSONArray no es iterable.
Así es como proceso elementos en una red .ficción.json.JSONArray :

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

Funciona muy bien... :)

 4
Author: Piko,
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-07-11 18:08:02

Java 8 está en el mercado después de casi 2 décadas, la siguiente es la forma de iterar org.json.JSONArray con java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

Si la iteración es solo una vez, (no es necesario .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });
 3
Author: prayagupd,
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-11-11 07:02:28

Al mirar tu código, presiento que estás usando JSONLIB. Si ese fue el caso, mire el siguiente fragmento para convertir matriz json a matriz java..

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  
 1
Author: Teja Kantamneni,
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
2009-10-14 21:14:29

En caso de que ayude a alguien más, Pude convertir a una matriz haciendo algo como esto,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...o usted debe ser capaz de obtener la longitud

((JSONArray) myJsonArray).toArray().length
 0
Author: wired00,
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-06-02 01:29:13

HashMap regs = (HashMap) parser.(stringjson);

(String) ((HashMap)regs.get("firstlevelkey")).get ("secondlevelkey");

 -1
Author: roger,
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-11-01 23:54:03