2012-04-05 5 views
7

meine Zeichenfolge ist:Gson deserialise Array von Name/Wert-Paare

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

kann ich Gson bekommen dies deserialise, ohne ihm zu hinzufügen/Einwickeln es? Grundsätzlich muss ich ein Array von Name-Wert-Paaren deserialisieren. Ich habe ein paar Ansätze versucht, ohne Erfolg.

+1

[Was * genau * hast du ausprobiert?] (Http://mattgemamm.com/2008/12/08/what-have-you-tried/) –

+0

Ich habe versucht, einen Collection-Typ zu definieren, zB Type collectionType = new TypeToken >() {}. GetType(); und auch dieser Ansatz http://stackoverflow.com/questions/9853017/parsing-json-array-with-gson – Black

+0

Die Lösung besteht darin, als ein Array von benutzerdefinierten Typ 'Sortieren' zu deserialisieren, z. B .: öffentliche Klasse Sort { private String-Eigenschaft; private String-Richtung; } Sortieren [] Sortieren = gson.fromJson (sortJson, Sortieren []. Klasse); – Black

Antwort

12

Sie wollen im Grunde ist es als Liste der Karten darzustellen:

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")); 
    } 
} 

Ausgang:

Nachnamen

Wenn die Objekte in Ihrem Array einen bekannten Satz von Schlüsseln enthalten/Wertepaare können Sie ein POJO erstellen und diesem zuordnen:

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; 
    }  
}