简体   繁体   English

如何使用Gson将JSON对象字符串转换为ArrayList?

[英]How can I convert a JSON string of objects into an ArrayList using Gson?

So I have a JSON string of countries like this: 所以我有一个像这样的国家的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
}

Now I want to have a method that tries to convert this into an ArrayList of countries. 现在我想要一个方法, 试图将其转换为国家的ArrayList

public static ArrayList<GFSCountry> get() {
    return new Gson().fromJson(countriesJson,  new TypeToken<ArrayList<GFSCountry>>(){}.getType());
}

But I get an 但我得到了一个

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path

As per request, here is my GFSCountry class: 根据要求,这是我的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;
}

I know I should adjust something either from the JSON string or the method. 我知道我应该从JSON字符串或方法调整一些东西。 Any help? 有帮助吗?

Since the list is nested in your JSON you will need a small mapping class that contains the list. 由于列表嵌套在JSON中,因此需要一个包含列表的小型映射类。

Try 尝试

static class GFSCountryList {
    public List<GFSCountry> details;
}

public static List<GFSCountry> get() {
    return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}

It seems to me that Gson is expecting your json to be like this 在我看来,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
 ]

But it encounters an object (marked by { }) 但它遇到一个对象(用{}标记)

Either you have the possibility to change your json format, or you create a class with a "details" attribut as a list to be compatible with the json's format. 要么你有可能改变你的json格式,要么创建一个带有“details”的类作为列表,以便与json的格式兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM