亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Java訪問JSONArray中的項成員

使用Java訪問JSONArray中的項成員

LEATH 2019-11-25 12:16:50
使用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 回答

?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

您是否嘗試過使用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-11-26
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

一個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-11-26
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

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-11-26
  • 3 回答
  • 0 關注
  • 301 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號