[英]Jackson serialize class name as property for all objects
I'd like the class name of all POJOs Jackson serializes to JSON objects to be included as a property of the respective object. 我想将所有POJO Jackson的类名序列化为JSON对象,以将其作为相应对象的属性包含在内。 Ideally, this should be achieved through some general setting of the ObjectMapper or similar. 理想情况下,这应该通过ObjectMapper或某些类似的常规设置来实现。
Serialization example: 序列化示例:
public class MyClass {
private String someField;
private MyOtherClass anotherField;
}
to 至
{
"$type": "MyClass",
"someField": "abc",
"anotherField": {
"$type": "MyOtherClass",
...
}
}
I know this could also be done by annotating all the respective classes with something like 我知道这也可以通过用类似的注释所有相应的类来完成
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "$type")
But I'd like to avoid that. 但我想避免这种情况。
I've also tried 我也尝试过
objectMapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, "$type")
which didn't seem to work. 这似乎没有用。
Is there such a general setting available? 有这样的常规设置吗?
EDIT: Thanks to AZWN's hints I actually got what I was looking for by customizing and constructing a TypeResolverBuilder
with DefaultTyping.NON_FINAL
. 编辑:感谢AZWN的提示,通过使用DefaultTyping.NON_FINAL
定制和构造TypeResolverBuilder
,我实际上得到了我想要的TypeResolverBuilder
。
StdTypeResolverBuilder typer = new ObjectMapper.DefaultTypeResolverBuilder(ObjectMapper.DefaultTyping.NON_FINAL) {
@Override
public boolean useForType(JavaType t) {
return !(t.isCollectionLikeType() || t.isMapLikeType()) && super.useForType(t);
}
}
.init(JsonTypeInfo.Id.NAME, null)
.inclusion(JsonTypeInfo.As.PROPERTY)
.typeProperty("$type");
objectMapper.setDefaultTyping(typer);
You should use ObjectMapper.DefaultTyping.NON_FINAL
instead of ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT
, since the latter one only includes type properties when the field type of a class is Object
at compile time . 您应该使用ObjectMapper.DefaultTyping.NON_FINAL
而不是ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT
,因为当编译时类的字段类型为Object
时,后者仅包括类型属性。
For more info, see the docs . 有关更多信息,请参阅docs 。 Also, be aware of the security issues they mention. 另外,请注意他们提到的安全问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.