簡體   English   中英

JAVA中JsonObjects的JsonObject

[英]JsonObject of JsonObjects in JAVA

我有一個充滿JSONobjectJSONObject ,我需要將它們中的每一個提取到一個新的JSONObject以便我可以單獨操作它們中的每一個,但我真的不知道該怎么做。 我的代碼是這樣的:

public void loadBodies(InputStream in) {

JSONObject jsonInput= new JSONObject(new JSONTokener(in));

JSONObject jo2 = jsonInput.getJSONObject("bodies"); //probably incorrect
for(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'
        }
        ]
}

我需要將 key bodies下的所有JSONObject提取到一組新的JSONObjects ,以便我可以對它們進行操作。 所以基本上,在循環中提取它們,但我不知道如何。

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

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
}

您可以這樣做並根據您的要求操作每個值。 每次在對象中找到任何 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);
  }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM