首页 > 解决方案 > 如何使用 Gson 将 JSON 对象字符串转换为 ArrayList?

问题描述

所以我有一个这样的国家的 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 字符串或方法中调整一些东西。有什么帮助吗?

标签: javajsonlistarraylistgson

解决方案


由于该列表嵌套在您的 JSON 中,您将需要一个包含该列表的小型映射类。

尝试

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

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

推荐阅读