java - 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。
解决方案
我最终以这种方式实现它:
@SerializedName("details")
@Expose
private JsonElement details;
我只是用来JsonParser
将内容解析为JsonElement
. 坚持GSON
所有这一切,尽管这不是理想的实现。将来会尝试实现自定义反序列化器。
推荐阅读
- docker - GitLab CI:iOS 项目问题(权限被拒绝)
- acumatica - 有没有办法在代码中模拟网格的同步位置?
- javascript - jQuery .width() 停止使用 .resize() 添加到变量
- sql-server-2016 - SQL 游标内的 IF-ELSE 更改记录的值
- docker - 使用 --net=container:containerName 键将 docker 容器附加到另一个容器的网络
- node.js - POST 请求在 Postman 中有效,但在浏览器中无效
- spring-boot - EmbeddedServletContainerCustomizer(spring 2 和 spring boot 2)更改为 WebServerFactoryCustomizer(spring 5 和 spring boot 2)
- vhdl - 从 FSM 在 UART 上发送
- c# - 如何从键值对的 JSON 数组中提取字节数组
- javascript - 根据字段 id 获取/过滤文档