反序列化List到HashMap jackson

发布于 2025-01-19 09:08:38 字数 933 浏览 0 评论 0原文

我有一个关于杰克逊的序列化/反序列化的问题。

我有一个带有这样的 Map(职业)的类:

public class RoomType implements Comparable<RoomType>, Serializable {

  private static final long serialVersionUID = 2310443507411437907L;
  // Key: idUseOccupation, Value: Occupation
  private Map<Long, Occupation> occupations = new LinkedHashMap<>();
 ...

并且该字段的 Getter 不是返回 Map,而是返回 Collection

  public Collection<Occupation> getOccupations() {
    return occupations.values();
  }

Setter:

  public void setOccupations(Map<Long, Occupation> occupations) {
    this.occupations = occupations;
  }

所以,我对序列化没有问题,但是当我尝试使用 Jackson 反序列化时roomType 对象,我收到错误: 无法从 START_ARRAY 令牌中反序列化 java.util.LinkedHashMap 实例。只是为了测试,我已将 getter 从 Collection 更改为 Map,并且检查它工作正常,但我无法进行此更改,因为这将意味着许多类中的多个更改,并且可能会在多个应用程序中引发如此大的问题。

我该如何解决这个问题?

提前致谢。

I have an issue regarding serialization/deserialization with jackson.

I have a class with a Map (occupations) like this:

public class RoomType implements Comparable<RoomType>, Serializable {

  private static final long serialVersionUID = 2310443507411437907L;
  // Key: idUseOccupation, Value: Occupation
  private Map<Long, Occupation> occupations = new LinkedHashMap<>();
 ...

and the Getter of this field instead of returning a Map, it's returning a Collection

  public Collection<Occupation> getOccupations() {
    return occupations.values();
  }

Setter:

  public void setOccupations(Map<Long, Occupation> occupations) {
    this.occupations = occupations;
  }

So, I have no problem with the serialization, but when I try to deserialize with jackson to a roomType object, I get an error:
Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token. Just for testing I have changed the getter from Collection to Map and I checked that it works fine, but I cannot make this change because it will imply multiple changes in lots of classes and it might provoke such a big issues in several applications.

How can I solve this problem?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文