简体   繁体   中英

JSON GSON.fromJson Java Objects

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);

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM