【问题标题】:Gson deserialize models within a wrapperGson 在包装器中反序列化模型
【发布时间】: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 。

标签: java json gson


【解决方案1】:

尝试替换:

ItemCollectionModel items;

与:

List<SingleItemModel> items;

【讨论】:

  • 你说得对,这将允许 Gson 反序列化响应,但需要集合类来确定要显示的视图类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
相关资源
最近更新 更多