我有以下课程:
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()
。请帮忙。
答案 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();