如何使用GSON将JSON字符串转换为对象集合?

时间:2013-03-08 17:48:55

标签: android json gson

我有以下课程:

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 = "";
   }
}

我有一个json字符串,如下所示:

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

我可以使用以下代码轻松地从Collection UserObject转换为JSON

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);

但我不确定如何将JSON string转换为collection的{​​{1}}?我发现我可以使用objects但不知道如何使用gson.fromJson()。请帮忙。

2 个答案:

答案 0 :(得分:5)

以下代码可让您获取Collection

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

此外,请注意,问题中提供的json无效,因为phoneno字段后有一个额外的逗号。这是正确的:

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

答案 1 :(得分:2)

鉴于此JSON,您的包装类应如下所示:

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

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

然后转换它,使用

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

要获取用户,请使用

List<User> users = data.getUsers();