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

标签 android json gson

我有以下类(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 = "";
   }
}

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

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

我可以使用以下代码轻松地将 UserObjectCollection 转换为 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 转换为 objectscollection?我发现我可以使用 gson.fromJson() 但不知道如何用于 Collection。请帮忙。

最佳答案

以下代码允许您获取 UserObjectCollection

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"
    }
]

关于android - 如何使用 GSON 将 JSON 字符串转换为对象集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15300179/

相关文章:

android - 在 Android 8 (Oreo) 中,Intent Chooser 无法设置 WallPaper

android - Visual Studio Cordova 工具,错误文件中的设备调试断点

java - 如何使用 Jackson ObjectMapper 检测尾随垃圾

java | Gson |将 JSON 对象添加到现有的 JSON 文件

java - gson 不会反序列化数组

json - GSON 抛出“预期为 BEGIN_OBJECT,但为 STRING

java - 如何减去以前的键值(存储在数据库中)

android - 按钮未显示在 LinearLayout 中

json - 从 Bitbucket 中检索文本文件内容

c# - Facebook C# SDK : Traverse The JsonArray To Get The Value of Tracking Data