2015-06-27 36 views
10

我已經將GSON用作Java中的JSON解析器,但密鑰並不總是相同。例如,
。我有以下的JSON:Java GSON:獲取JSONObject下所有密鑰的列表

{ 「我已經知道了對象」:{
「KEY1」: 「值1」,
「KEY2」: 「值2」,
「AnotherObject」:{「 anotherKey1 「:」 anotherValue1" , 「anotherKey2」: 「anotherValue2」}
}

我已經得到了JSONObject的 「我已經知道了對象」。現在我需要獲取該對象的所有JSON元素,這將是「Key1」,「Key2」和「AnotherObject」。
在此先感謝。
編輯:輸出應該是一個字符串數組與JSONObject的所有鍵

+0

的可能重複[如何使用Gson解碼未知字段的JSON?](http://stackoverflow.com/questions/20442265/how-to-decode-json-with-unknown-field-using-gson) – pkubik

+0

這可能是有用的http://stackoverflow.com/questions/14619811/retrieving-all-the-keys-in-a-nested-json-in-java –

+0

什麼應該是你的最終輸出?它應該是,「key1」,「key2」,「AnotherObject」或「我已經知道的對象」,「key1」,「key2」,「AnotherObject」'? –

回答

38

您可以使用JsonParser將您的Json轉換爲允許您檢查json內容的中間結構。

String yourJson = "{your json here}"; 
JsonParser parser = new JsonParser(); 
JsonElement element = parser.parse(yourJson); 
JsonObject obj = element.getAsJsonObject(); //since you know it's a JsonObject 
Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object 
for (Map.Entry<String, JsonElement> entry: entries) { 
    System.out.println(entry.getKey()); 
} 
+0

JsonParser是一個相當棘手的小野獸:) –

+1

爲什麼不obj.keySet()? – Zon

+0

obj.keySet()似乎是一個更好的選擇 – mkamioner

4
String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}"; 

     JsonParser parser = new JsonParser(); 
     JsonObject jObj = (JsonObject)parser.parse(str); 

     List<String> keys = new ArrayList<String>(); 
     for (Entry<String, JsonElement> e : jObj.entrySet()) { 
      keys.add(e.getKey()); 
     } 

     // keys contains jsonObject's keys 
10

由於Java 8,你可以使用流爲更好地尋找替代方案:

String str = "{\"key1\":\"val1\", \"key2\":\"val2\"}"; 

JsonParser parser = new JsonParser(); 
JsonObject jObj = (JsonObject) parser.parse(str); 

List<String> keys = jObj.entrySet() 
    .stream() 
    .map(i -> i.getKey()) 
    .collect(Collectors.toCollection(ArrayList::new)); 

keys.forEach(System.out::println); 
4

由於GSON 2.8.1您可以使用keySet()

String json = "{\"key1\":\"val\", \"key2\":\"val\"}"; 

JsonParser parser = new JsonParser(); 
JsonObject jsonObject = parser.parse(json).getAsJsonObject(); 

Set<String> keys = jsonObject.keySet();