I have following 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 = "";
}
}
I have a json
string like following:
[
{
"id": 1,
"name": "First Name",
"phoneno": "0123452",
},
{
"id": 2,
"name": "Second Name",
"phoneno": "0123452",
},
{
"id": 3,
"name": "Third Name",
"phoneno": "0123455",
}
]
I can easily convert from Collection
of UserObject
to JSON
using following code:
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);
But I am not sure how to convert the JSON
string
to the collection
of objects
? I have found that I can use gson.fromJson()
but don't know how to use for Collection
. Please help.
The following code allows you to get the Collection
of UserObject
Type token = new TypeToken<Collection<UserObject>>() {}.getType();
Collection<UserObject> result = gson.fromJson(json, token);
Also, please note that the json
provided in the question isn't valid, because there is a extra comma after phoneno
field. Here is the corrent one:
[
{
"id": 1,
"name": "First Name",
"phoneno": "0123452"
},
{
"id": 2,
"name": "Second Name",
"phoneno": "0123452"
},
{
"id": 3,
"name": "Third Name",
"phoneno": "0123455"
}
]
Given this JSON, your wrapper class should look like this:
public class Data {
private List<User> users;
// +getters/setters
}
public class User {
private String name;
private String email;
private List<User> friends;
// +getters/setters
}
and then to convert it, use
Data data = gson.fromJson(this.json, Data.class);
and to get the users, use
List<User> users = data.getUsers();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With