2013-10-03 22 views
17

Sto cercando di analizzare alcuni dati JSON utilizzando gson in Java che ha la seguente struttura, ma guardando gli esempi online, non riesco a trovare nulla che faccia il lavoro.Analisi dei dati JSON nidificati utilizzando GSON

Qualcuno potrebbe essere in grado di assistere?

{ 
    "data":{ 
     "id":[ 
      { 
       "stuff":{ 

       }, 
       "values":[ 
        [ 
         123, 
         456 
        ], 
        [ 
         123, 
         456 
        ], 
        [ 
         123, 
         456 
        ], 

       ], 
       "otherStuff":"blah" 
      } 
     ] 
    } 
} 

risposta

39

Hai solo bisogno di creare una struttura di classi Java che rappresenti i dati nel tuo JSON. Per fare questo, vi suggerisco di copiare il vostro JSON in questo online JSON Viewer e vedrai la struttura del JSON molto più chiara ...

Fondamentalmente è necessario queste classi (pseudo-codice):

class Response 
    Data data 

class Data 
    List<ID> id 

class ID 
    Stuff stuff 
    List<List<Integer>> values 
    String otherStuff 

Nota che i nomi degli attributi nelle tue classi devono corrispondere ai nomi dei tuoi campi JSON! Puoi aggiungere più attributi e classi in base alla tua reale struttura JSON ... Inoltre, tieni presente che hai bisogno di getter e setter per tutti i tuoi attributi!

Infine, non vi resta che analizzare il JSON nella vostra struttura di classe Java con:

Gson gson = new Gson(); 
Response response = gson.fromJson(yourJsonString, Response.class); 

E il gioco è fatto! Ora è possibile accedere a tutti i dati all'interno dell'oggetto response utilizzando i getter e setter ...

Per esempio, al fine di accedere al primo valore 456, è necessario fare:

int value = response.getData().getId().get(0).getValues().get(0).get(1); 
+0

Colgo la libertà di suggerirti http://json.parser.online.fr/, ha individuato anche un errore di sintassi su Json fornito da PO. – giampaolo

+0

Penso che [link] [http://www.jsonschema2pojo.org] sia davvero utile per prendere una risposta JSON e creare oggetti Java per te! –

8

A seconda di cosa si sta tentando di fare. Potresti semplicemente installare un gerarchia POJO che corrisponda al tuo json come visto here (metodo preferito). In alternativa, è possibile fornire un numero personalizzato deserializer. Mi sono occupato solo dei dati id come presumo fosse la difficile implementazione in questione. È sufficiente scorrere lo json utilizzando i tipi gson e creare i dati che si sta tentando di rappresentare. Le classi Data e Id sono solo pojos composte e corrispondenti alle proprietà nella stringa originale json.

public class MyDeserializer implements JsonDeserializer<Data> 
{ 

    @Override 
    public Data deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException 
    { 
    final Gson gson = new Gson(); 
    final JsonObject obj = je.getAsJsonObject(); //our original full json string 
    final JsonElement dataElement = obj.get("data"); 
    final JsonElement idElement = dataElement.getAsJsonObject().get("id"); 
    final JsonArray idArray = idElement.getAsJsonArray(); 

    final List<Id> parsedData = new ArrayList<>(); 
    for (Object object : idArray) 
    { 
     final JsonObject jsonObject = (JsonObject) object; 
     //can pass this into constructor of Id or through a setter 
     final JsonObject stuff = jsonObject.get("stuff").getAsJsonObject(); 
     final JsonArray valuesArray = jsonObject.getAsJsonArray("values"); 
     final Id id = new Id(); 
     for (Object value : valuesArray) 
     { 
     final JsonArray nestedArray = (JsonArray)value; 
     final Integer[] nest = gson.fromJson(nestedArray, Integer[].class); 
     id.addNestedValues(nest); 
     } 
     parsedData.add(id); 
    } 
    return new Data(parsedData); 
    } 

}

prova:

@Test 
    public void testMethod1() 
    { 
    final String values = "[[123, 456], [987, 654]]"; 
    final String id = "[ {stuff: { }, values: " + values + ", otherstuff: 'stuff2' }]"; 
    final String jsonString = "{data: {id:" + id + "}}"; 
    System.out.println(jsonString); 
    final Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new MyDeserializer()).create(); 
    System.out.println(gson.fromJson(jsonString, Data.class)); 
    } 

Risultato:

Data{ids=[Id {nestedList=[[123, 456], [987, 654]]}]} 

POJO:

public class Data 
{ 

    private List<Id> ids; 

    public Data(List<Id> ids) 
    { 
    this.ids = ids; 
    } 

    @Override 
    public String toString() 
    { 
    return "Data{" + "ids=" + ids + '}'; 
    } 
} 


public class Id 
{ 

    private List<Integer[]> nestedList; 

    public Id() 
    { 
    nestedList = new ArrayList<>(); 
    } 

    public void addNestedValues(final Integer[] values) 
    { 
    nestedList.add(values); 
    } 

    @Override 
    public String toString() 
    { 
    final List<String> formattedOutput = new ArrayList(); 
    for (Integer[] integers : nestedList) 
    { 
    formattedOutput.add(Arrays.asList(integers).toString()); 
    } 
    return "Id {" + "nestedList=" + formattedOutput + '}'; 
    } 
} 
Problemi correlati