How to parse json in modification using dynamic key

I have this answer, and I want to make it a model class with a modification. I know how to make a model class for each specific object, but I don’t know how to make a model class for the first parent array.

[3]
0:  {
     user: {
            _id: "55e725b65656565d066037"
            photo: "https://graph.facebook.com/9884898989882/picture?height=300&width=300"
            provider: "facebook"
            username: "xyz"
           }
        url:"abc.com"
    }
1:  {
     user: {
            _id: "55e725b65656565d066037"
            photo: "https://graph.facebook.com/9884898989882/picture?height=300&width=300"
            provider: "facebook"
            username: "xyz"
           }
        url:"abc.com"
    }
2:  {
     user: {
            _id: "55e725b65656565d066037"
            photo: "https://graph.facebook.com/9884898989882/picture?height=300&width=300"
            provider: "facebook"
            username: "xyz"
           }
        url:"abc.com"
    }
+4
source share
1 answer

If your json looks like this:

{
    "0": {
        "user": {
            "_id": "55e725b65656565d066037",
            "photo": "https://graph.facebook.com/9884898989882/picture?height=300&width=300",
            "provider": "facebook",
            "username": "xyz"
        },
        "url": "abc.com"
    },
    "1": {
        "user": {
            "_id": "55e725b65656565d066037",
            "photo": "https://graph.facebook.com/9884898989882/picture?height=300&width=300",
            "provider": "facebook",
            "username": "xyz"
        },
        "url": "abc.com"
    },
    "2": {
        "user": {
            "_id": "55e725b65656565d066037",
            "photo": "https://graph.facebook.com/9884898989882/picture?height=300&width=300",
            "provider": "facebook",
            "username": "xyz"
        },
        "url": "abc.com"
    }
}

You can create a model for the elements "0", "1", etc.

public class Element {

    private User user;

    private String url;

    public User getUser() {
        return user;
    }

    public String getUrl() {
        return url;
    }

    public static class User {

        @SerializedName("_id")
        private String id;

        private String photo;

        private String provider;

        private String username;

        public String getId() {
            return id;
        }

        public String getPhoto() {
            return photo;
        }

        public String getProvider() {
            return provider;
        }

        public String getUsername() {
            return username;
        }
    }
}

And finally, you need to create a map for the top level json

Map<String, Element> elements;

You can get the items as below:

elements.get("0");
-1
source

Source: https://habr.com/ru/post/1618686/


All Articles