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.
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");
// ...
}
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... :)
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);
});
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 );
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
HashMap regs = (HashMap) parser.parse (stringjson);
(chaîne) ( HashMap ) Règl.get ("firstlevelkey")).get ("secondlevelkey");