0

I have a JSON response coming back from my server in the format:

[
    {
        "id": "one",
        "values": {
            "name": "John",
        }
    },
    {
        "id": "two",
        "values": {
            "name": "Bob",
        }
    }
]

Here is the class I've set up:

public class TestClass implements Serializable {

    @SerializedName("id")
    private String id;

    @SerializedName("values")
    private List<String> values;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }
}

Here is my code to parse the JSON into a list of objects:

String response = serverResponseHere;
Gson gson = new Gson();
String json = gson.toJson(response);

Type collectionType = new TypeToken<List<TestClass>>(){}.getType();
List<TestClass> values = gson.fromJson(json, collectionType);

However, I get the following error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING

What's going on here?

user984648
  • 71
  • 1
  • 6

2 Answers2

0

You're taking your JSON response content

String response = serverResponseHere;

and converting it to JSON

Gson gson = new Gson();
String json = gson.toJson(response);

This produces a JSON string containing your content. That looks like

"[\n    {\n        \"id\": \"one\",\n        \"values\": {\n            \"name\": \"John\",\n        }\n    },\n    {\n        \"id\": \"two\",\n        \"values\": {\n            \"name\": \"Bob\",\n        }\n    }\n]\n"

When you try to deserialize that as a List<TestClass>, it obviously fails because it's a JSON String instead of a JSON Array.

Don't serialize your content to JSON before deserializing it, it's already JSON.


Others have mentioned this, your values field doesn't match what your JSON content. See here for how to fix that:

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
-2

Change your server response json from :

[
    {
        "id": "one",
        "values": {
            "name": "John",
        }
    },
    {
        "id": "two",
        "values": {
            "name": "Bob",
        }
    }
]

To :

[
    {
        "id": "one",
        "values": [
            {"name": "John"}
        ]
    },
    {
        "id": "two",
        "values": [
            {"name": "Bob"}
        ]
    }
]
Koustuv Ganguly
  • 897
  • 7
  • 21