2015-06-27 10 views
10

Ho ottenuto GSON come parser JSON in Java, ma le chiavi non sono sempre le stesse.
Ad esempio. Ho il seguente JSON:Java GSON: Ottenere l'elenco di tutte le chiavi in ​​un JSONObject

{ "l'oggetto so già": {
"key1": "value1",
"key2": "valore2",
"AnotherObject": { " anotherKey1 ":" anotherValue1" , "anotherKey2": "anotherValue2"}}

ho già ottenuto il JSONObject "l'oggetto so già". Ora ho bisogno di ottenere tutti i JSONElements per questo oggetto, questo sarebbe "Key1", "Key2" e "AnotherObject".
Grazie in anticipo.
EDIT: L'output dovrebbe essere una matrice di stringhe con tutte le chiavi per la JSONObject

+0

possibile duplicato di [ Come decodificare JSON con campo sconosciuto usando Gson?] (Http://stackoverflow.com/questions/20442265/how-to-decode-json-with-unknown-field-using-gson) – pkubik

+0

questo potrebbe essere utile http://stackoverflow.com/questions/14619811/retrieving-all-the-keys-in-a-ested-json-in-java –

+0

quale dovrebbe essere il risultato finale? dovrebbe essere, '" key1 "," key2 "," AnotherObject "' OR '" L'oggetto so già "," key1 "," key2 "," AnotherObject "' ?? –

risposta

38

È possibile utilizzare JsonParser per convertire la vostra JSON in una struttura intermedia che consentono di esaminare il contenuto 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 è piuttosto una piccola bestia insidiosa :) –

+1

Perché non obj.keySet()? – Zon

+0

obj.keySet() sembra essere una scelta migliore – 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

Dal momento che Java 8 è possibile utilizzare Streams come alternativa più bello:

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

A partire dal 2.8.1 GSON è possibile utilizzare keySet():

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

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

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