无法使用Gson解析Json数组

时间:2013-07-15 09:02:53

标签: java android json gson

我有这个json数组:

 [
{
"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);

但是我收到了这个错误:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.deliveries.models.MapData

我做错了什么?

2 个答案:

答案 0 :(得分:32)

我怀疑调用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

中有一个完整的问题示例

答案 1 :(得分:-1)

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