Acessando os membros de itens em um JSONArray com Java
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
o meu código:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
tenho acesso ao JSONArray" record "neste momento, mas não sei como obter os valores" id "e" loc " dentro de um laço for. Desculpe se esta descrição não é muito clara, Eu sou um pouco novo para a programação.
6 answers
Você já tentou usar [JSONArray.getJSONObject(int)
](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)), e [JSONArray.length()
](http://json.org/javadoc/org/json/JSONArray.html#length()) para criar o seu loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
An org.json.JSONArray não é iterável.
Aqui está como eu processo elementos em uma rede .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");
...
}
Funciona muito bem... :)
Java 8 está no mercado após quase 2 décadas, seguindo é o caminho para iterate {[[2]} com 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
}
Se a iteração for apenas uma vez, (não é necessário .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
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 );
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...ou você deve ser capaz de obter o comprimento
((JSONArray) myJsonArray).toArray().length
HashMap regs = (HashMap) parser.parse (stringjson);
(Texto) ((HashMap )regs.get ("firstlevelkey").get ("secondlevelkey");