Accès aux membres d'articles dans un JSONArray avec Java

je commence juste à utiliser JSON avec java. Je ne sais pas comment accéder aux valeurs des chaînes de caractères 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" record "JSONArray à ce point, mais je ne suis pas sûr de savoir 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 à la programmation.

98
demandé sur Michael A. Jackson 2009-10-15 00:25:14

6 réponses

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 pour-boucle:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}
187
répondu notnoop 2009-10-14 20:32:32

Un org.json.JSONArray n'est pas itérable.

Voici comment je traite les éléments dans un filet .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
répondu Piko 2013-07-11 18:08:02

Java 8 est sur le marché Après presque 2 décennies, suivant est la façon d'itérer org.json.JSONArray avec L'API java8 Stream.

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 n'est qu'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
répondu prayagupd 2017-11-11 07:02:28

en regardant votre code, je sens que vous utilisez JSONLIB. Si c'était le cas, regardez l'extrait suivant pour convertir JSON array en Java array..

 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
répondu Teja Kantamneni 2009-10-14 21:14:29

dans le cas où il aide quelqu'un d'autre, J'ai été capable de convertir à un tableau en faisant quelque chose comme ceci,

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

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

((JSONArray) myJsonArray).toArray().length
0
répondu wired00 2015-06-02 01:29:13

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

(chaîne) ( HashMap ) Règl.get ("firstlevelkey")).get ("secondlevelkey");

-1
répondu roger 2017-11-01 23:54:03