Dale Julian
Dale Julian

Reputation: 1588

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

So I have a JSON string of countries like this:

{
"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.

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:

@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. Any help?

Upvotes: 1

Views: 85

Answers (2)

FrontierPsychiatrist
FrontierPsychiatrist

Reputation: 1433

Since the list is nested in your JSON you will need a small mapping class that contains the list.

Try

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

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

Upvotes: 2

S&#233;bastien Palud
S&#233;bastien Palud

Reputation: 81

It seems to me that Gson is expecting your json to be like this

 [
    {
        "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.

Upvotes: 1

Related Questions