为了账号安全,请及时绑定邮箱和手机立即绑定

使用Java访问JSONArray中的项成员

使用Java访问JSONArray中的项成员

慕婉清6462132 2019-07-24 15:06:59
使用Java访问JSONArray中的项成员我刚刚开始在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”值。对不起,如果这个描述不太清楚,我对编程有点新意。
查看完整描述

3 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

您是否尝试过使用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");
    // ...}


查看完整回答
反对 回复 2019-07-24
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

一个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");
        ...
    }

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


查看完整回答
反对 回复 2019-07-24
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

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

import org.json.JSONArray;import org.json.JSONObject;@Testpublic 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);
            });


查看完整回答
反对 回复 2019-07-24
  • 3 回答
  • 0 关注
  • 769 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号