How to convert JSON string to object collection using GSON?

android, gson, json

Solution

The following code allows you to get the `Collection` of `UserObject`

Type token = new TypeToken<Collection<UserObject>>() {}.getType();
Collection<UserObject> result = gson.fromJson(json, token);

Also, please note that the `json` provided in the question isn't valid, because there is a extra comma after `phoneno` field. Here is the corrent one:

[
    {
        "id": 1,
        "name": "First Name",
        "phoneno": "0123452"
    },
    {
        "id": 2,
        "name": "Second Name",
        "phoneno": "0123452"
    },
    {
        "id": 3,
        "name": "Third Name",
        "phoneno": "0123455"
    }
]

Problem

I have following class: ``` public class UserObject implements Serializable { public Integer id; public String name; public String phoneno; public UserObject() { this.id = new Integer(0); this.name = ""; this.phoneno = ""; } } ``` I have a `json` string like following: ``` [ { "id": 1, "name": "First Name", "phoneno": "0123452", }, { "id": 2, "name": "Second Name", "phoneno": "0123452", }, { "id": 3, "name": "Third Name", "phoneno": "0123455", } ] ``` I can easily convert from `Collection` of `UserObject` to `JSON` using following code: ``` Collection users = new Vector(); UserObject userObj = new UserObject(); userObj.id=1; userObj.name="First Name"; userObj.phoneno="0123451"; users.add(userObj); userObj.id=2; userObj.name="Second Name"; userObj.phoneno="0123452"; users.add(userObj); userObj.id=3; userObj.name="Second Name"; userObj.phoneno="0123455"; users.add(userObj); Gson gson = new Gson(); String json = gson.toJson(users); ``` But I am not sure how to convert the `JSON` `string` to the `collection` of `objects`? I have found that I can use `gson.fromJson()` but don't know how to use for `Collection`. Please help.

Original source