JSON GSON.fromJson Java Objects

后端 未结 1 1078
臣服心动
臣服心动 2020-11-29 07:19

I am trying to load my Json into my class

public User() {
    this.fbId = 0;
    this.email = \"\";
    this.name =          


        
相关标签:
1条回答
  • 2020-11-29 07:53

    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();
    
    0 讨论(0)
提交回复
热议问题