JSON GSON.fromJson Java Objects

我想把我的Json加载到我的class级

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

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 users; // +getters/setters } public class User { private String name; private String email; private List friends; // +getters/setters } 

然后转换它,使用

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

并获得用户,使用

 List users = data.getUsers();