使用 Java 访问 JSON 数组中项目的成员

2022-08-31 08:26:27

我刚刚开始将json与java一起使用。我不确定如何访问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

你有没有试过使用 JSONArray.getJSONObject(int)JSONArray.length() 来创建你的 for-loop:

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

答案 2

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

效果很好... :)