用于学习目的我想使用retrofit和Gson构建一个简单的android REST客户端。 这是我要解析的Json字符串:
{
"kind": "Listing",
"data": {
"modhash": "qo2fwmjj5iee4adde638f97d5a7063087439bf4985aab4c9a5",
"children": [
{
"kind": "t5",
"data": {
"banner_img": "",....
我的数据模型:
public class Response {
@SerializedName("kind")
private String kind;
@SerializedName("data")
private Data data;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
@SerializedName("modhash")
private String modhash;
@SerializedName("after")
private String after;
@SerializedName("before")
private String before;
@SerializedName("children")
private List<Child> children;
public String getModhash() {
return modhash;
}
public void setModhash(String modhash) {
this.modhash = modhash;
}
public String getAfter() {
return after;
}
public void setAfter(String after) {
this.after = after;
}
public String getBefore() {
return before;
}
public void setBefore(String before) {
this.before = before;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
public class Child {
@SerializedName("kind")
private String kind;
@SerializedName("data")
private List<Sub> data;
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public List<Sub> getData() {
return data;
}
public void setData(List<Sub> data) {
this.data = data;
}
}
单元测试:
public class Test {
private GsonConverter gsonConverter;
private Gson gson;
private Logger logger = Logger.getLogger(Test.class.getName());
public Test() {
gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
gsonConverter = new GsonConverter(gson);
}
@Test
public void testData() {
Response response = gson.fromJson(TestUtil.RESPONSE_STRING, Response.class);
logger.info("Data " + response.getData());
Assert.assertNotNull(response.getData());
}
}
所以当解析器到达&#34;孩子时#34;属性,发生以下错误。
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
at com.google.gson.internal.bind.JsonTreeReader.expect(JsonTreeReader.java:139)
at com.google.gson.internal.bind.JsonTreeReader.beginArray(JsonTreeReader.java:58)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read
不知道该怎么做,尝试过不同的事情,我是否必须处理孩子们的问题。我自己因为[括号?
答案 0 :(得分:1)
data
类中的字段Child
不应该是列表。它是json中的一个对象,所以在数据模型中使它成为对象。