我收到了这个JSON字符串:
{
"response": [
346,
{
"id": 564,
"from_id": -34454802,
"to_id": -34454802,
"date": 1337658196,
"post_type": "post"
},
{
"id": 2183,
"from_id": -34454802,
"to_id": -34454802,
"date": 1423916628,
"post_type": "post"
},
{
"id": 2181,
"from_id": -34454802,
"to_id": -34454802,
"date": 1423724270,
"post_type": "post"
}]
}
我创建了以下类:
public class Response {
@SerializedName("response")
ArrayList<Post> posts;
}
public class Post {
int id;
int from_id;
int to_id;
long date;
String post_type;
}
当我尝试解析响应时,我收到错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 19 path $.response[0]
这是因为数组的第一个元素是Number。操作时需要哪种型号没有错误?
答案 0 :(得分:1)
直接使用Converter默认GsonConverter可以直接使用改造功能进行改造。这就是为什么需要自定义Converter实现的原因。
这篇文章using-gson-to-parse-array-with-multiple-types应该有助于实施。
设置转换器只需使用:
RestAdapter getRestAdapter(...) {
return new RestAdapter.Builder()
...
.setConverter(converter)
...
.build();
}
答案 1 :(得分:1)
你的模型类应该是这样的,模型对象总是应该像带有类对象或String对象的字符串或ArrayList。如果你提到int
,你将获得illegalState异常。
public class Pojo
{
private Response[] response;
public Response[] getResponse ()
{
return response;
}
public void setResponse (Response[] response)
{
this.response = response;
}
}
public class Response
{
private String id;
private String to_id;
private String from_id;
private String post_type;
private String date;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getTo_id ()
{
return to_id;
}
public void setTo_id (String to_id)
{
this.to_id = to_id;
}
public String getFrom_id ()
{
return from_id;
}
public void setFrom_id (String from_id)
{
this.from_id = from_id;
}
public String getPost_type ()
{
return post_type;
}
public void setPost_type (String post_type)
{
this.post_type = post_type;
}
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
}