如何使用动态密钥在改造中解析json

时间:2015-12-05 09:44:53

标签: android json retrofit

我有这个回复,我想使用改造来制作它的模型类。我知道如何为每个特定对象制作模型类,但不知道如何为第一个父数组创建模型类。

[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"
    }

1 个答案:

答案 0 :(得分:-1)

如果你的json看起来像:

{
    "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"
    }
}

您可以为元素" 0"," 1"等创建模型。

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

最后你必须为顶级json级别创建Map

Map<String, Element> elements;

您可以获得如下元素:

elements.get("0");