JSON GSON.fromJson Java Objects
gson, java, json
Solution
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();
Problem
I am trying to load my Json into my 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' } } } } } } } ``` I am struggling to get GSON to load the user details into the above Java object with the following code ``` User user = gson.fromJson(this.json, User.class); ```