java– 无法使用Gson解析Json数组

java– 无法使用Gson解析Json数组,第1张

概述我有这个json数组:[{"id":18,"city":"הרצליה","street":"החושלים1","zipcode":121209,"state":"IL","lat":32.158138,"lng":34.807838},{"id":19,

我有这个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对象的List:

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

我究竟做错了什么?

解决方法:

我怀疑调用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中有一个完整的问题例子

总结

以上是内存溢出为你收集整理的java – 无法使用Gson解析Json数组全部内容,希望文章能够帮你解决java – 无法使用Gson解析Json数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1101094.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存