2011-09-05 93 views
35

我有以下格式的JSON結果,其中JSON Lint顯示爲「有效響應」。如何解析嵌套JSON結果中的動態JSON密鑰?

我的問題是:如何訪問「question_mark」的內容,因爲「141」,「8911」等都是動態值?

我的示例代碼用於訪問「產品」的價值。

//Consider I have the first <code>JSONObject</code> of the "search_result" array and 
//I access it's "product" value as below. 
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject. 
//<code>product<code> now contains "abc". 

JSON:

{ 
"status": "OK", 
"search_result": [ 

      { 
       "product": "abc", 
       "id": "1132", 
       "question_mark": { 
        "141": { 
         "count": "141", 
         "more_description": "this is abc", 
         "seq": "2" 
        }, 
        "8911": { 
         "count": "8911", 
         "more_desc": "this is cup", 
         "seq": "1" 
        } 
       }, 
       "name": "some name", 
       "description": "This is some product" 
      }, 
      { 
       "product": "XYZ", 
       "id": "1129", 
       "question_mark": { 
        "379": { 
         "count": "379", 
         "more_desc": "this is xyz", 
         "seq": "5" 
        }, 
        "845": { 
         "count": "845", 
         "more_desc": "this is table", 
         "seq": "6" 
        }, 
        "12383": { 
         "count": "12383", 
         "more_desc": "Jumbo", 
         "seq": "4" 
        }, 
        "257258": { 
         "count": "257258", 
         "more_desc": "large", 
         "seq": "1" 
        } 
       }, 
       "name": "some other name", 
       "description": "this is some other product" 
      } 
     ] 
} 

我的問題標題「動態密鑰」可能是錯的,但我不知道在這一點上有什麼針對此問題的更好的名字。

任何幫助將不勝感激!

+0

我想你應該執行前具有內部question_mark對象的值。你有嗎? –

+0

umm,no。我不知道如何訪問問號​​內的值。爲此,我必須做jsonObj.optJSONObject(「141」); 141是動態的,我不會提前知道它。 –

回答

99

使用JSONObject keys()獲取密鑰,然後迭代每個密鑰以獲得動態值。

大致代碼如下:


    // searchResult refers to the current element in the array "search_result" 
    JSONObject questionMark = searchResult.getJSONObject("question_mark"); 
    Iterator keys = questionMark.keys(); 

    while(keys.hasNext()) { 
     // loop to get the dynamic key 
     String currentDynamicKey = (String)keys.next(); 

     // get the value of the dynamic key 
     JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); 

     // do something here with the value... 
    } 

+0

+1太棒了!這工作得很好!我看到你的早期回覆,其中提示使用keys(),我最終打印出外鍵。如果不是你的示例代碼,我最終會問另一個問題! :P再次感謝您的及時響應!高時間SO支持多個upvotes一個偉大的答案! –

+1

很高興能夠幫助:)如果您有任何問題,請告訴我。我們(SO社區)都在這裏幫助 – momo

+0

我用過你的代碼一次,在這裏我再次爲另一個榮譽momo –

11

另一種可能性是使用Gson(注意,我這裏用龍目生成getter/setter方法,的toString等):

package so7304002; 

import java.util.List; 
import java.util.Map; 

import lombok.AccessLevel; 
import lombok.Data; 
import lombok.NoArgsConstructor; 

import com.google.gson.Gson; 
import com.google.gson.annotations.SerializedName; 
import com.google.gson.reflect.TypeToken; 

@NoArgsConstructor(access = AccessLevel.PRIVATE) 
public final class JsonDemo { 
    @Data 
    private static class MyMap { 
     private int count; 

     @SerializedName("more_description") 
     private String moreDescription; 

     private int seq; 
    } 

    @Data 
    private static class Product { 
     private String product; 

     private int id; 

     @SerializedName("question_mark") 
     private Map<String, MyMap> questionMark; 
    } 

    @Data 
    private static class MyObject { 
     private String status; 

     @SerializedName("search_result") 
     private List<Product> searchResult; 
    } 

    private static final String INPUT = ""; // your JSON 

    public static void main(final String[] arg) { 
     final MyObject fromJson = new Gson().fromJson(INPUT, 
      new TypeToken<MyObject>(){}.getType()); 
     final List<Product> searchResult = fromJson.getSearchResult(); 
     for (final Product p : searchResult) { 
      System.out.println("product: " + p.getProduct() 
       + "\n" + p.getQuestionMark()+ "\n"); 
     } 
    } 
} 

輸出:

product: abc 
{141=JsonDemo.MyMap(count=141, moreDescription=this is abc, seq=2), 
8911=JsonDemo.MyMap(count=8911, moreDescription=null, seq=1)} 

product: XYZ 
{379=JsonDemo.MyMap(count=379, moreDescription=null, seq=5), 
845=JsonDemo.MyMap(count=845, moreDescription=null, seq=6), 
12383=JsonDemo.MyMap(count=12383, moreDescription=null, seq=4), 
257258=JsonDemo.MyMap(count=257258, moreDescription=null, seq=1)} 
+0

感謝您對GSON,RC有用的信息和教程。 +1爲創建完整代碼示例做出額外努力 - 這對其他人也會有所幫助。 –

0

同樣的事情也可以做usin g GSON,而不是使用GSON轉換器適配器轉換爲POJO。我們將手動解析它。這爲我們提供了動態JSON數據的靈活性。
比方說,我的情況下,JSON格式如下所示。

{ 
    "dateWiseContent": { 
    "02-04-2017": [ 
     { 
     "locality": " Cross Madian Cross Rd No 4" 
     } 
    ], 
    "04-04-2017": [ 
     { 
     "locality": "Dsilva Wadi" 
     }, 
     { 
     "locality": " Cross Madian Cross Rd No 4", 
     "appointments": [] 
     } 
    ] 
    } 
} 
在這種情況下

dateWiseContent動態對象鍵 所以我們將解析使用JsonParser類此JSON字符串。

//parsing string response to json object 
JsonObject jsonObject = (JsonObject) new JsonParser().parse(resource); 
    //getting root object 
JsonObject dateWiseContent = jsonObject.get("dateWiseContent").getAsJsonObject(); 

得到使用Map.Entry<String, JsonElement>動態密鑰下

// your code goes here 
     for (Map.Entry<String, JsonElement> entry : dateWiseContent.entrySet()) { 

      //this gets the dynamic keys 
      String dateKey = entry.getKey(); 

      //you can get any thing now json element,array,object according to json. 

      JsonArray jsonArrayDates = entry.getValue().getAsJsonArray(); 
      int appointmentsSize = jsonArrayDates.size(); 

      for (int count = 0; count < appointmentsSize; count++) { 

        JsonObject objectData = jsonArrayDates.get(count).getAsJsonObject(); 
        String locality = objectData.get("locality").getAsString(); 


      } 
     } 

使用Map.Entry<String,JsonElement>

0

使用從Google Gson

JSON數據的例子類似的動態JSON的任何水平可以被解析爲給定問題:

{ 
    "status": "OK", 
    "search_result": [ 
     { 
      "product": "abc", 
      "id": "1132", 
      "question_mark": { 
       "141": { 
        "count": "141", 
        "more_description": "this is abc", 
        "seq": "2" 
       }, 
       "8911": { 
        "count": "8911", 
        "more_desc": "this is cup", 
        "seq": "1" 
       } 
      }, 
      "name": "some name", 
      "description": "This is some product" 
     }, 
     { 
      "product": "XYZ", 
      "id": "1129", 
      "question_mark": { 
       "379": { 
        "count": "379", 
        "more_desc": "this is xyz", 
        "seq": "5" 
       }, 
       "845": { 
        "count": "845", 
        "more_desc": "this is table", 
        "seq": "6" 
       }, 
       "12383": { 
        "count": "12383", 
        "more_desc": "Jumbo", 
        "seq": "4" 
       }, 
       "257258": { 
        "count": "257258", 
        "more_desc": "large", 
        "seq": "1" 
       } 
      }, 
      "name": "some other name", 
      "description": "this is some other product" 
     } 
    ] 
} 

示例代碼:

import com.google.gson.Gson; 
import com.google.gson.JsonArray; 
import com.google.gson.JsonElement; 
import com.google.gson.JsonObject; 

public class GsonExercise { 
    public static void main(String[] args) { 
     String jsonString = "{\"status\":\"OK\",\"search_result\":[{\"product\":\"abc\",\"id\":\"1132\",\"question_mark\":{\"141\":{\"count\":\"141\",\"more_description\":\"this is abc\",\"seq\":\"2\"},\"8911\":{\"count\":\"8911\",\"more_desc\":\"this is cup\",\"seq\":\"1\"}},\"name\":\"some name\",\"description\":\"This is some product\"},{\"product\":\"XYZ\",\"id\":\"1129\",\"question_mark\":{\"379\":{\"count\":\"379\",\"more_desc\":\"this is xyz\",\"seq\":\"5\"},\"845\":{\"count\":\"845\",\"more_desc\":\"this is table\",\"seq\":\"6\"},\"12383\":{\"count\":\"12383\",\"more_desc\":\"Jumbo\",\"seq\":\"4\"},\"257258\":{\"count\":\"257258\",\"more_desc\":\"large\",\"seq\":\"1\"}},\"name\":\"some other name\",\"description\":\"this is some other product\"}]}"; 
     JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class); 
     JsonArray ja = jobj.get("search_result").getAsJsonArray(); 
     ja.forEach(el -> { 
      System.out.println("product: " + el.getAsJsonObject().get("product").getAsString()); 
      JsonObject jo = el.getAsJsonObject().get("question_mark").getAsJsonObject();    
      jo.entrySet().stream().forEach(qm -> { 
       String key = qm.getKey(); 
       JsonElement je = qm.getValue(); 
       System.out.println("key: " + key); 
       JsonObject o = je.getAsJsonObject(); 
       o.entrySet().stream().forEach(prop -> { 
        System.out.println("\tname: " + prop.getKey() + " (value: " + prop.getValue().getAsString() + ")"); 
       }); 
      }); 
      System.out.println(""); 
     }); 
    } 
} 

輸出:

product: abc 
key: 141 
    name: count (value: 141) 
    name: more_description (value: this is abc) 
    name: seq (value: 2) 
key: 8911 
    name: count (value: 8911) 
    name: more_desc (value: this is cup) 
    name: seq (value: 1) 

product: XYZ 
key: 379 
    name: count (value: 379) 
    name: more_desc (value: this is xyz) 
    name: seq (value: 5) 
key: 845 
    name: count (value: 845) 
    name: more_desc (value: this is table) 
    name: seq (value: 6) 
key: 12383 
    name: count (value: 12383) 
    name: more_desc (value: Jumbo) 
    name: seq (value: 4) 
key: 257258 
    name: count (value: 257258) 
    name: more_desc (value: large) 
    name: seq (value: 1)