使用改装将 json 解析为 POJO

parsing json to POJO using retrofit

我正在尝试使用改装将 json 解析为 POJO,但一直出现错误。 它似乎获取了数据,据我从 logcat 中看到的,我正确地读取和解析了 json。但它 returns succes=false 而不是 return responsedata 对象。 错误类型和错误消息显示为空。 我不知道哪里出了问题,如果有任何解决方案或如何定位错误的建议,我将不胜感激。

Json

{
  "competition_info": {
    "headline": "competition",
    "description": "description for competition.",
    "accept_button": "OK",
    "open_terms_button": "Open info"
  },
  "terms": {
    "html": "a website in html"
  }
    }

MyPojo

public class AnnComResponses{
    @SerializedName("competition_info")
    public CompetitionInfo competitionInfo;
    @SerializedName("terms")
    public Terms terms;

    public class Terms{

        @SerializedName("html")
        public String html;

        public String getTerms() {
            return html;
        }
    }

    public class CompetitionInfo{
        @SerializedName("headline")
        public String headline;
        @SerializedName("description")
        public String description;
        @SerializedName("accept_button")
        public String acceptButton;
        @SerializedName("open_terms_button")
        public String openTermsButton;

        public String getHeadline() {
            return headline;
        }

        public String getDescription() {
            return description;
        }

        public String getAcceptButton() {
            return acceptButton;
        }

        public String getOpenTermsButton() {
            return openTermsButton;
        }

    }
}

首先,您的主 class 中有几个 class。将它们分成单独的文件,不要将它们放在同一个 class 中。其次,在您的主要 class 中,您需要为您的属性 competitionInfo 和 terms 添加 setter 和 getter。同样作为一种好的风格,将属性设为私有,并且您的 getter 和 setter 保持 public.

尝试使用 GSON 转换器进行改造,如下所示:

RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setConverter(new GsonConverter(new GsonBuilder()).create()))
                .setEndpoint("your api end point goes here")
                .build(); 
YourAPI api = restAdapter.create(YourAPI.class);