杰克逊序列化地图与额外的字段 [英] Jackson serialise map with extra fields

查看:89
本文介绍了杰克逊序列化地图与额外的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类扩展了Map并包含一些额外的字段。 EG是最后修改日期,杰克逊似乎忽略了任何未作为地图属性包含的内容。

If a class extends a Map and includes some extra fields. E.G a last modified date, Jackson seems to ignore any thing not contained as a property of the map.

我有一个看起来如下的类:

I have a class that looks some thing like the following:

import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Objects;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Foo extends HashMap<String, String> {

   private OffsetDateTime lastModifiedTime;

   public Foo() {
      super();
      lastModifiedTime = OffsetDateTime.now();
   }

   public void setLastModifiedTime(OffsetDateTime newTime) {
      this.lastModifiedTime = newTime;
   }

   public OffsetDateTime getLastModifiedTime() {
      return this.lastModifiedTime;
   }

   public static void main(String[] args) throws IOException {
      Foo f = new Foo();
      f.put("hello", "world");

      ObjectMapper om = new ObjectMapper();
      om.findAndRegisterModules();

      String result = om.writeValueAsString(f);
      if(f.equals(om.readValue(result, Foo.class))) {
         System.out.println("Wooo");
      } else {
         System.out.println("Booo: " + result);
      }

   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj) {
         return true;
      }
      if (!(obj instanceof Foo)) {
         return false;
      }
      if (!super.equals(obj)) {
         return false;
      }
      Foo foo = (Foo) obj;
      return Objects.equals(getLastModifiedTime(), foo.getLastModifiedTime());
   }

   @Override
   public int hashCode() {
      return Objects.hash(super.hashCode(), getLastModifiedTime());
   }

}

运行时输出 booo:{hello:world} 其中不包括上次修改日期。

When this runs it outputs booo: {"hello":"world"} Which does not include the last modified date.

我尝试将 @JsonInclude 注释添加到属性和getter但不会导致它包括额外的字段。

I've tried adding @JsonInclude annotations to the property and the getters but that doesn't cause it to include the extra field.

让Jackson包含这个额外字段的正确方法是什么?

What is the correct way to make Jackson include this extra field?

推荐答案

扩展HashMap通常被认为是不好的做法。相反,您应该创建一个具有地图的类,以及附加字段。

It's generally considered bad practice to extend HashMap. Instead, you should create a class that has a Map, and the additional field.

这将解决您的问题,但也会有额外的优点:

This will solve your problem, but will also have additional advantages:


  • 您将能够封装规则(例如阻止添加某些键/值等)。

  • 如果需要,您可以更改Map实现(LinkedHashMap,同步地图,并发地图)

这篇关于杰克逊序列化地图与额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆