【发布时间】:2019-03-04 13:14:21
【问题描述】:
我有一个 JSON 响应从我的服务器返回,格式为:
[
{
"id": "one",
"values": {
"name": "John",
}
},
{
"id": "two",
"values": {
"name": "Bob",
}
}
]
这是我设置的课程:
public class TestClass implements Serializable {
@SerializedName("id")
private String id;
@SerializedName("values")
private List<String> values;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
这是我将 JSON 解析为对象列表的代码:
String response = serverResponseHere;
Gson gson = new Gson();
String json = gson.toJson(response);
Type collectionType = new TypeToken<List<TestClass>>(){}.getType();
List<TestClass> values = gson.fromJson(json, collectionType);
但是,我收到以下错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 应为 BEGIN_ARRAY 但为 STRING
这是怎么回事?
【问题讨论】:
-
根据您的值,它只是对象数组而不是列表字符串
-
将对象用作列表导致错误。这是正确的: = Type collectionType = new TypeToken
(){}.getType(); .你儿子也错了