2012-04-05 2 views
7

mia stringa è:GSON a deserialise serie di nomi di coppie/valore

"[{"property":"surname","direction":"ASC"}]" 

posso ottenere GSON a deserialise questo, senza aggiungere ad essa/avvolgendolo? Fondamentalmente, ho bisogno di deserializzare un array di coppie nome-valore. Ho provato alcuni approcci, senza successo.

+1

[Cosa * esattamente * hai provato?] (Http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+0

Ho provato a definire un tipo di raccolta, ad esempio Type collectionType = new TypeToken >() {}. GetType(); e anche questo approccio http://stackoverflow.com/questions/9853017/parsing-json-array-with-gson – Black

+0

La soluzione è deserializzare come una matrice di tipo personalizzato 'Ordina', ad esempio: classe pubblica Ordina { proprietà String privata; direzione String privata; } Ordina [] sort = gson.fromJson (sortJson, Sort []. Class); – Black

risposta

12

Che, fondamentalmente, vogliono rappresentare come elenco di mappe:

public static void main(String[] args) 
{ 
    String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]"; 

    Type listType = new TypeToken<ArrayList<HashMap<String,String>>>(){}.getType(); 

    Gson gson = new Gson(); 

    ArrayList<Map<String,String>> myList = gson.fromJson(json, listType); 

    for (Map<String,String> m : myList) 
    { 
     System.out.println(m.get("property")); 
    } 
} 

uscita:

cognome

Se gli oggetti in vostro array contengono una serie nota di chiave/coppie di valori, è possibile creare un POJO e mappare a quello:

public class App 
{ 
    public static void main(String[] args) 
    { 
     String json = "[{\"property\":\"surname\",\"direction\":\"ASC\"}]"; 
     Type listType = new TypeToken<ArrayList<Pair>>(){}.getType(); 
     Gson gson = new Gson(); 
     ArrayList<Pair> myList = gson.fromJson(json, listType); 

     for (Pair p : myList) 
     { 
      System.out.println(p.getProperty()); 
     } 
    } 
} 

class Pair 
{ 
    private String property; 
    private String direction; 

    public String getProperty() 
    { 
     return property; 
    }  
}