使用 Jackson MixIn 添加 属性?

Adding a property using Jackson MixIn's?

我知道我们可以使用 Jackson MixIn 重命名 属性 或忽略 属性(参见示例 here)。但是可以加一个属性吗?

添加的属性可以是:

  1. 常量(例如版本号)
  2. 一个计算值(例如,如果源 class 具有 getWidth()getHeight() 的属性,但我们想忽略两者并改为导出 getArea()
  3. 来自嵌套成员的扁平化信息(例如 class 有一个成员 Information,后者又有一个成员 Description,我们想要一个新的 属性对于 description 并跳过 Information)
  4. 的嵌套结构

来自 documentation:

"Mix-in" annotations are a way to associate annotations with classes, without modifying (target) classes themselves, originally intended to help support 3rd party datatypes where user can not modify sources to add annotations.

With mix-ins you can:
1. Define that annotations of a '''mix-in class''' (or interface)
2. will be used with a '''target class''' (or interface) such that it appears
3. as if the ''target class'' had all annotations that the ''mix-in'' class has (for purposes of configuring serialization / deserialization)

要解决您的问题,您可以:

  • 新建 POJO,其中包含所有必填字段。
  • 实施自定义序列化程序。
  • 在序列化之前将 POJO 转换为 Map 和 add/remove 节点。
  • 使用 com.fasterxml.jackson.databind.ser.BeanSerializerModifier 扩展自定义序列化程序。参见:.

例如,要为每个对象添加一个常量版本,您可以将其包装在 Verisoned class:

class Versioned {

    private final String version;

    @JsonUnwrapped
    private final Object pojo;

    public Versioned(String version, Object pojo) {
        this.version = version;
        this.pojo = pojo;
    }

    public String getVersion() {
        return version;
    }

    public Object getPojo() {
        return pojo;
    }
}

现在,如果包装一个 Arae(width, height) 对象:

Area area = new Area(11, 12);
String json = mapper.writeValueAsString(new Versioned("1.1", area));

输出将是:

{
  "version" : "1.1",
  "width" : 11,
  "height" : 12
}