JSON GSON.fromJson Java Objects
The JSON is invalid. A collection is not to be represented by {}
. It stands for an object. A collection/array is to be represented by []
with commaseparated objects.
Here's how the JSON should look like:
{
users:[{
name: "name1",
email: "email1",
friends:[{
name: "name2",
email: "email2",
friends:[{
name: "name3",
email: "email3"
},
{
name: "name4",
email: "email4"
}]
}]
}]
}
(note that I added one more friend to the deepest nested friend, so that you understand how to specify multiple objects in a collection)
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();