Accès aux membres des éléments dans un JSONArray avec Java


Je commence juste à utiliser json avec java. Je ne sais pas comment accéder aux valeurs de chaîne dans un JSONArray. Par exemple, mon json ressemble à ceci:

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

Mon code:

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

J'ai accès au JSONArray "record" à ce stade, mais je ne sais pas comment j'obtiendrais les valeurs "id" et "loc" dans une boucle for. Désolé si cette description n'est pas trop claire, je suis un peu nouveau dans la programmation.

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

6 answers

Avez-vous essayé d'utiliser [JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)), et [JSONArray.length()](http://json.org/javadoc/org/json/JSONArray.html#length()) pour créer votre boucle 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, 2009-10-14 20:32:32

Une organisation .json.JSONArray n'est pas itérable.
Voici comment je traite les éléments dans un net.sf.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");
        ...
    }

Fonctionne très bien... :)

 4
Author: Piko, 2013-07-11 18:08:02

Java 8 est sur le marché après presque 2 décennies, voici la façon d'itérer org.json.JSONArray avec l'API de flux java8.

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 l'itération est une seule fois, (pas besoin de .collect)

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

En regardant votre code, je sens que vous utilisez JSONLIB. Si tel était le cas, regardez l'extrait de code suivant pour convertir le tableau json en tableau 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, 2009-10-14 21:14:29

Au cas où cela aiderait quelqu'un d'autre, J'ai pu convertir en un tableau en faisant quelque chose comme ça,

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

...ou vous devriez être en mesure d'obtenir la longueur de

((JSONArray) myJsonArray).toArray().length
 0
Author: wired00, 2015-06-02 01:29:13

HashMap regs = (HashMap) analyseur.parse(stringjson);

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

 -1
Author: roger, 2017-11-01 23:54:03