我正在尝试将我的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);
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();