【问题标题】:Android: Cannot deserialize json into class object with GsonAndroid:无法使用 Gson 将 json 反序列化为类对象
【发布时间】:2021-12-03 04:41:46
【问题描述】:

给定下一个json:

{
   "alpha_two_code":"AR",
   "web_pages":[
      "http://www.atlantida.edu.ar/"
   ],
   "name":"Universidad Atlantida Argentina",
   "country":"Argentina",
   "domains":[
      "atlantida.edu.ar"
   ],
   "state-province":null
}

我正在尝试将其反序列化为一个 College 对象,如下所示:

public class College
{
    @SerializedName(value = "name")
    private String college;
    @SerializedName(value = "country")
    private String country;
    @SerializedName(value = "state-province")
    private String state;
    private Web_Pages web_pages;

    public College()
    {

    }

    public String getCollege()
    {
        return college;
    }

    public String getCountry()
    {
        return country;
    }

    public String getState()
    {
        return state;
    }

    public static class Web_Pages
    {
        private String[] url;

        public String[] getUrl()
        {
            return url;
        }

        public void setUrl(String[] url)
        {
            this.url = url;
        }
    }
}

我正在尝试像这样反序列化:

College college = new Gson().fromJson(String.valueOf(json), College.class);

但总是抛出下一个异常:

Expected BEGIN_OBJECT but was BEGIN_ARRAY in web_pages

任何帮助 om 如何处理这个问题?

【问题讨论】:

    标签: android json gson deserialization


    【解决方案1】:

    好的,我自己发现了问题。与其拥有内部 Web_Pages 类,不如使用 String[] 对象,所以我的类定义现在看起来像这样:

    public class College {
        @SerializedName(value = "name")
        private String college;
        @SerializedName(value = "country")
        private String country;
        @SerializedName(value = "state-province")
        private String state;
        private String[] web_pages;
    
        public College() {
    
        }
    
        public String getCollege() {
            return college;
        }
    
        public String getCountry() {
            return country;
        }
    
        public String getState() {
            return state;
        }
        
        public String[] getWeb_pages(){
            return web_pages;
        }
    }
    

    希望它可以帮助其他面临同样问题的人:)

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多