【问题标题】:How to parse json in retrofit with dynamic key如何使用动态密钥在改造中解析 json
【发布时间】:2016-03-10 06:38:26
【问题描述】:

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

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

【问题讨论】:

  • 使用这个。将你的整个 json 响应源粘贴到其中,它会给你一个完整的模型类 jsonschema2pojo.org

标签: android json retrofit


【解决方案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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2017-10-03
    相关资源
    最近更新 更多