Acessando os membros de itens em um JSONArray com Java

Estou a começar a usar o json com java. Não sei como aceder aos valores das cordas dentro de um JSONArray. Por exemplo, o meu json parece-se com isto:
{
  "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.

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

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");
    // ...
}
 187
Author: notnoop, 2009-10-14 20:32:32

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... :)

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

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);
            });
 3
Author: prayagupd, 2017-11-11 07:02:28
Ao olhar para o teu código, sinto que estás a usar o JSONLIB. Se esse foi o caso, olhe para o seguinte excerto para converter JSON array para 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
Author: Teja Kantamneni, 2009-10-14 21:14:29
No caso de ajudar outra pessoa., Consegui Converter-me a uma matriz fazendo algo assim.
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...ou você deve ser capaz de obter o comprimento

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

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

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

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