Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON string to object collection using GSON?

Tags:

json

android

gson

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.

like image 609
ray Avatar asked Jan 15 '23 00:01

ray


2 Answers

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"
    }
]
like image 155
Vladimir Mironov Avatar answered Jan 19 '23 22:01

Vladimir Mironov


Given this JSON, your wrapper class should look like this:

public class Data {
    private List<User> users;
    // +getters/setters
}

public class User {
    private String name;
    private String email;
    private List<User> friends;
    // +getters/setters
}

and then to convert it, use

Data data = gson.fromJson(this.json, Data.class);

and to get the users, use

List<User> users = data.getUsers();
like image 41
DjHacktorReborn Avatar answered Jan 19 '23 22:01

DjHacktorReborn