【发布时间】:2017-02-10 08:47:11
【问题描述】:
我在包装类中收集了一组潜在的 JSON 响应模型,例如这个仪表板示例:
public class Dashboard {
@SerializedName("dashboard")
private List<Wrapper> wrappers;
public class Wrapper {
LocalDateTime updated;
SingleItemModel item;
ItemCollectionModel items;
//....
}
}
public class ItemCollectionModel {
List<SingleItemModel> items;
}
我正在尝试从几个 API 端点的聚合 JSON 中填充这些字段。缩写形式类似于:
{
"dashboard": [
{
"updated": "2017-02-08T05:42:52.451",
"items": {...}
},
"updated": "2017-02-08T05:42:52.451",
"item": {...}
},
....
]
}
我遇到了 Gson 无法创建 POJO 的问题。如果我的理解是正确的,默认反序列化会尝试将字段名称与 JSON 元素键匹配。
"items" : {} to ItemCollectionModel items
我认为问题在于实例字段的命名与对应的 Wrappers 类似。
Wrapper.items vs ItemCollectionModel.items
当 API 响应为单个 POJO 时,Gson 反序列化非常有效,它将封装的 JSON 对象视为 POJO,并且 JSON 的内部值与 POJO 字段匹配。但是在尝试使用 Wrapper 时,我得到了空字段。
如何确保 Wrapper 的字段被正确反序列化?
------------更新-------------
一个简单的解决方案是盯着我的脸。根据 jakubbialkowski 的回答,使用对象列表允许 Gson 反序列化这些项目。诀窍是在调用该字段的 getter 时手动创建 CollectionModel 来封装它。
public ItemCollectionModel getItemCollectionModel() {
return new ItemCollectionModel(items);
}
【问题讨论】:
-
你可以在线生成pojos来传递你的json。
-
您能对此提供更多解释吗?
-
要从 json 为 gson 制作正确的 pojo 结构,请将您的 json 响应传递给 jsonschema2pojo.org 这个链接并选择 Source type: and Annotation style: at right side 。