问题

我刚刚开始在java中使用json。我不确定如何在JSONArray中访问字符串值。例如,我的json看起来像这样:

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

我的代码:

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

此时我可以访问"记录"JSONArray,但我不确定如何在for循环中获取"id"和"loc"值。对不起,如果这个描述不太清楚,我对编程有点新意。


#1 热门回答(187 赞)

你是否尝试使用JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)))和JSONArray.length()](http://json.org/javadoc/org/json/JSONArray.html#length())))创建你的for循环:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

#2 热门回答(4 赞)

Anorg.json.JSONArray不可迭代。
以下是我在anet.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");
        ...
    }

效果很好...... :)


#3 热门回答(3 赞)

Java 8在近二十年后进入市场,以下是使用java8 Stream API迭代org.json.JSONArray的方法。

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
}

如果迭代只有一次,(不需要.collect)

IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

原文链接