我正在尝试使用Retrofit2和GSON解析Wordpress plugins API的JSON结果。我使用众所周知的website生成了我的POJO并将其修改为以下模型:
PluginsApiResponse.java
public class PluginsApiResponse {
@SerializedName("plugins")
@Expose
private List<Plugin> plugins = null;
public List<Plugin> getPlugins() {
return plugins;
}
public void setPlugins(List<Plugin> plugins) {
this.plugins = plugins;
}
}
Plugin.java
public class Plugin {
@SerializedName("name")
@Expose
private String name;
@SerializedName("homepage")
@Expose
private String homepage;
@SerializedName("screenshots")
@Expose
private Screenshots screenshots;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHomepage() {
return homepage;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
public Screenshots getScreenshots() {
return screenshots;
}
public void setScreenshots(Screenshots screenshots) {
this.screenshots = screenshots;
}
}
Screenshots.java
public class Screenshots {
@SerializedName("1")
@Expose
private com.dkalsan.retrofitwordpress._1 _1;
@SerializedName("2")
@Expose
private com.dkalsan.retrofitwordpress._2 _2;
@SerializedName("3")
@Expose
private com.dkalsan.retrofitwordpress._3 _3;
public com.dkalsan.retrofitwordpress._1 get1() {
return _1;
}
public void set1(com.dkalsan.retrofitwordpress._1 _1) {
this._1 = _1;
}
public com.dkalsan.retrofitwordpress._2 get2() {
return _2;
}
public void set2(com.dkalsan.retrofitwordpress._2 _2) {
this._2 = _2;
}
public com.dkalsan.retrofitwordpress._3 get3() {
return _3;
}
public void set3(com.dkalsan.retrofitwordpress._3 _3) {
this._3 = _3;
}
}
_1.java (_2.java和_3.java完全相同)
public class _1 {
@SerializedName("src")
@Expose
private String src;
@SerializedName("caption")
@Expose
private String caption;
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
如果屏幕截图字段不包含任何条目,则会出现此问题。我已经设置了HttpLoggingInterceptor,它完整地记录了响应代码200和json。我还根据以下article排除了它成为互联网连接问题的可能性。如果我从模型中删除屏幕截图字段,则解析没有问题。由于GSON尝试反序列化不存在的字段 1 , 2 和 3 ,错误可能仍然存在,如果是,如何处理用它?
答案 0 :(得分:0)
结果问题出在JSON响应格式中。如果没有截图,则将其格式化为JSON数组,否则将其格式化为包含对象1,2,3等的JSON对象。我已设法通过遵循this stackoverflow question上的答案来修复它