所以我有一个像这样的国家的JSON字符串:
{
"details": [
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
}
现在我希望有一个尝试的方法将其转换为ArrayList
个国家/地区。
public static ArrayList<GFSCountry> get() {
return new Gson().fromJson(countriesJson, new TypeToken<ArrayList<GFSCountry>>(){}.getType());
}
但我得到了
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path
根据要求,这是我的GFSCountry
课程:
@SerializedName("country_id")
@Expose
private String countryId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("regions")
@Expose
private Object regions;
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getRegions() {
return regions;
}
public void setRegions(Object regions) {
this.regions = regions;
}
我知道我应该从JSON字符串或方法调整一些东西。有什么帮助吗?
答案 0 :(得分:2)
由于列表嵌套在JSON中,因此需要一个包含列表的小型映射类。
尝试
static class GFSCountryList {
public List<GFSCountry> details;
}
public static List<GFSCountry> get() {
return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}
答案 1 :(得分:1)
在我看来,Gson期待你的json像这样
[
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
]
但遇到一个对象(标有{})
要么你有可能改变你的json格式,要么创建一个带有“details”的类作为列表,以便与json的格式兼容。