使用Java访问JSONArray中的项成员

min*_*pop 114 java arrays json

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

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我的代码:

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

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

not*_*oop 208

您是否尝试过使用JSONArray.getJSONObject(int)JSONArray.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");
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Pik*_*iko 5

一个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");
        ...
    }
Run Code Online (Sandbox Code Playgroud)

效果很好... :)

  • 这对我不起作用,因为`JSONArray`是不可迭代的。 (10认同)
  • [org.json.JSONArray](http://www.json.org/javadoc/org/json/JSONArray.html)不可迭代,但是[net.sf.json.JSONArray](http:// json-lib .sourceforge.net / apidocs / net / sf / json / JSONArray.html)是可迭代的 (7认同)