我知道我们可以使用 Jackson MixIn 来重命名属性或忽略属性(参见示例 here )。但是可以添加属性吗?
添加的属性可以是:
getWidth()
和 getHeight()
的属性,但我们想忽略两者并导出 getArea()
) Information
,而该成员又具有一个成员 Description
,我们希望为 description
拥有一个新属性并跳过 06761914 的嵌套结构)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
并添加/删除节点。 com.fasterxml.jackson.databind.ser.BeanSerializerModifier
扩展自定义序列化程序。见:Jackson custom serialization and deserialization . 例如,要为每个对象添加一个常量版本,您可以将其包装在
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
}
关于jackson - 使用 Jackson MixIn 添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642660/