2013-07-15 63 views
8

我有這樣的JSON數組解析JSON數組:無法使用GSON

[ 
{ 
"id":18, 
"city":"הרצליה", 
"street":"החושלים 1", 
"zipcode":121209, 
"state":"IL", 
"lat":32.158138, 
"lng":34.807838 
}, 
{ 
"id":19, 
"city":"הרצליה", 
"street":"אבא אבן 1", 
"zipcode":76812, 
"state":"IL", 
"lat":32.161041, 
"lng":34.810410 
} 
] 

,我有這個類來保存數據:

public class MapData { 
    private int id; 
    private String city; 
    private String street; 
    private String state; 
    private int zipcode; 
    private double lat; 
    private double lng; 

    public MapData(int id, String city, String street, String state, 
      int zipcode, double lat, double lng) {   
     this.id = id; 
     this.city = city; 
     this.street = street; 
     this.state = state; 
     this.zipcode = zipcode; 
     this.lat = lat; 
     this.lng = lng; 
    } 

    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public String getCity() { 
     return city; 
    } 
    public void setCity(String city) { 
     this.city = city; 
    } 
    public String getStreet() { 
     return street; 
    } 
    public void setStreet(String street) { 
     this.street = street; 
    } 
    public String getState() { 
     return state; 
    } 
    public void setState(String state) { 
     this.state = state; 
    } 
    public int getZipcode() { 
     return zipcode; 
    } 
    public void setZipcode(int zipcode) { 
     this.zipcode = zipcode; 
    } 
    public double getLat() { 
     return lat; 
    } 
    public void setLat(double lat) { 
     this.lat = lat; 
    } 
    public double getLng() { 
     return lng; 
    } 
    public void setLng(double lng) { 
     this.lng = lng; 
    } 

} 

我試圖將JSON轉換成屬於MapData對象的列表:

Type type = new TypeToken<List<MapData>>(){}.getType(); 
return gson.fromJson(jsonString, type); 

,但我得到這個錯誤:

​​

我在做什麼錯?

+2

類型擦除工作的完整示例。 Gson知道他必須反序列化java.util.List,但不知道應該將什麼對象放入它,因此他使用內部類型。 –

+0

@ŁukaszLech - 但我告訴它,它的名單和根據Gson文檔,這是做到這一點?! – Tomer

+0

您的方法返回'MapData'或'List '?我懷疑你可能會返回錯誤的類型。 –

回答

31

我懷疑調用fromJson的方法正在返回錯誤的類型。它應該返回List<MapData>而不是MapData

喜歡的東西:

public static List<MapData> getData(){ 
    Gson gson = new Gson(); 
    String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]"; 
    Type type = new TypeToken<List<MapData>>(){}.getType(); 
    return gson.fromJson(jsonString, type);  
} 

我有你的問題,在這個Gist

+0

謝謝,我會檢查它,如果它的工作,我會將它標記爲正確的答案 – Tomer

+0

搜索2天后,終於得到了正確的方法來解決。非常感謝凱文! – PsyGik

-1
string Json="some Json String"; 
JavaScriptSerializer Js = new JavaScriptSerializer(); 
MapData ObjMapDat = new MapData(); 
ObjMapDat =Js.Deserialize<MapData>(Json);