我刚刚开始在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");
此时我可以访问"record“JSONArray,但不确定如何在for循环中获取"id”和"loc“值。如果这个描述不太清楚,很抱歉,我对编程有点新手。
发布于 2009-10-14 20:32:32
您是否尝试过使用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");
// ...
}
发布于 2009-11-11 02:09:32
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");
...
}
效果很好。:)
发布于 2017-06-06 06:36:30
java8在近20年后上市,下面是用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);
});
https://stackoverflow.com/questions/1568762
复制相似问题