[英]How to convert this json String to normal java arraylist using gson
[英]How can I convert a JSON string of objects into an ArrayList using Gson?
所以我有一個像這樣的國家的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字符串或方法調整一些東西。 有幫助嗎?
由於列表嵌套在JSON中,因此需要一個包含列表的小型映射類。
嘗試
static class GFSCountryList {
public List<GFSCountry> details;
}
public static List<GFSCountry> get() {
return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}
在我看來,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的格式兼容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.