首页 > 解决方案 > Retrofit 2.0:如何映射不同类型的对象

问题描述

这是我的示例 JSON 响应:

{
"success": true,
"details": {
    "banners": [
        {
            "banner_id": "1",
            "file_id": "368",
            "title": "INANG KALIKASAN'S BAD HAIR DAY",
            "description": "Et aeterno partiendo his, vim ponderum abhorreant et. Eum debet recusabo repudiandae in.",
            "created": "2018-03-09 07:56:04",
            "modified": "2018-04-02 09:59:54",
            "deleted": "",
            "file_name": "https://globegfs.imgix.net/uploads/2018-04-02/8a90371e9ad33cf06848b354b1fbd795.jpg",
            "orig_file_name": "hero-1.jpg"
        }
    ],
    "recent_books": [
        {
            "content_id": "353",
            "category_id": "24",
            "title": "One Hundred Fourth Symphony, in D-major",
            "author": "Franz Josef Haydn",
            "description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
            "tags": [
                {
                    "content_id": "353",
                    "tag_id": "14",
                    "created": "2018-04-27 15:57:46",
                    "tag_name": "Ray Collections"
                }
            ]
        }
    ],
    "classics": [
        {
            "content_id": "353",
            "category_id": "24",
            "title": "One Hundred Fourth Symphony, in D-major",
            "author": "Franz Josef Haydn",
            "description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
            "tags": [
                {
                    "content_id": "353",
                    "tag_id": "14",
                    "created": "2018-04-27 15:57:46",
                    "tag_name": "Ray Collections"
                }
            ]
        }
    ]
}

}

只有banners对象具有不同的内容列表。所有后续的 Json 元素都将具有相同的内容,但在一个列表中,其 Json 节点为其实际的title. 如何将其映射到 HashMap 中?

我想它看起来像这样:

private List<GFSBannerResponse> banners;
private List<HashMap<String, List<GFSContentResponse>>> featuredContent;

但我仍然不知道如何实现这一点。我正在使用 Retrofit 2.0 和 Gson。

标签: javaandroidjsonhashmapretrofit2

解决方案


我最终以这种方式实现它:

@SerializedName("details")
@Expose
private JsonElement details;

我只是用来JsonParser将内容解析为JsonElement. 坚持GSON所有这一切,尽管这不是理想的实现。将来会尝试实现自定义反序列化器。


推荐阅读