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

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

JAVA中JsonObjects的JsonObject

JAVA中JsonObjects的JsonObject

慕沐林林 2022-07-20 10:35:19
我有一個JSONObject完整的JSONobjects,我需要將它們中的每一個提取到一個新的中JSONObject,以便我可以單獨操作它們中的每一個,但我真的不知道該怎么做。我的代碼是這樣的:public void loadBodies(InputStream in) {JSONObject jsonInput= new JSONObject(new JSONTokener(in));JSONObject jo2 = jsonInput.getJSONObject("bodies"); //probably incorrectfor(JSonObject j: jo2) b.create(j); //i need to apply the create method to all the JSONObjects想象這樣的 JSON{'bodies': [        {            'total': 142250.0,             '_id': 'BC'        },         {            'total': 210.88999999999996,             '_id': 'USD'        },         {            'total': 1065600.0,             '_id': 'TK'        }        ]}我需要將JSONObject鍵下的所有 s提取bodies到一個新的集合中JSONObjects,以便我可以對它們進行操作。所以基本上,循環提取它們,但我不知道如何。
查看完整描述

2 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

根據您的示例,bodies是一個 JSON 數組。所以使用JSONArray庫org.json:json來迭代數組的內容:


String     json      = "{\"bodies\": [{\"total\": 142250.0, \"_id\": \"BC\"}]}";


JSONObject jsonInput = new JSONObject(new JSONTokener(new StringReader(json)));

JSONArray  array     = jsonInput.getJSONArray("bodies");

for (int i = 0; i < array.length(); i++) {

    JSONObject obj = array.getJSONObject(i);

     // implement here your logic on obj

}


查看完整回答
反對 回復 2022-07-20
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

您可以這樣做并根據您的要求操作每個值。每次在對象中找到任何 JSONObject 或 JSONArray 時,都會遞歸調用此方法。用于操作特定鍵值的 handleValue() 方法。


public void handleJSON(Object input, Map<String,Object> result ){

if (input instanceof JSONObject) {

  List < String > keys = new ArrayList < > (((JSONObject) input).keySet());

  for (String key: keys) {

    if (!(((JSONObject) input).get(key) instanceof JSONArray))

      if (((JSONObject) input).get(key) instanceof JSONObject) {

        handleJSONObject(((JSONObject) input).get(key), map);

      } else {

        Object value = ((JSONObject) input).get(key);

        ((JSONObject) input).put(key, handleValue(value, map));

      }

    else

      handleJSONObject(new JSONArray(((JSONObject) input).get(key).toString()), map);

  }


}

if (input instanceof JSONArray) {

  for (int i = 0; i < ((JSONArray) input).length(); i++) {

    JSONObject jsonObject = ((JSONArray) input).getJSONObject(i);

    handleJSONObject(jsonObject, map);

  }

}

}


查看完整回答
反對 回復 2022-07-20
  • 2 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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