JSON GSON.fromJson Java Objects

时间:2011-03-15 16:31:35

标签: java json gson

我正在尝试将我的Json加载到我的班级

public User() {
    this.fbId = 0;
    this.email = "";
    this.name = "";
    this.thumb = "";
    this.gender = "";
    this.location = "";
    this.relationship = null;
    this.friends = new ArrayList();
}
{
    users:{
        user:{
            name:'the name',
            email:'some@email.com',
            friends:{
                user:{
                    name:'another name',
                    email:'this@email.com',
                    friends:{
                        user:{
                            name:'yet another name',
                            email:'another@email.com'
                        }
                    }
                }
            }
        }
    }
}

我正在努力让GSON使用以下代码将用户详细信息加载到上面的Java对象中

User user = gson.fromJson(this.json, User.class);

1 个答案:

答案 0 :(得分:35)

JSON无效。集合不由{}表示。它代表对象。集合/数组由[]表示,并带有逗号分隔的对象。

以下是JSON的外观:

{
    users:[{
        name: "name1",
        email: "email1",
        friends:[{
            name: "name2",
            email: "email2",
            friends:[{
                name: "name3",
                email: "email3"
            },
            {
                name: "name4",
                email: "email4"
            }]
        }]
    }]
}

(请注意,我向最深的嵌套朋友添加了一位朋友,以便您了解如何在集合中指定多个对象)

鉴于此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();