在不更改POJO的情况下向REST端点提供多态反序列化/序列化参数 [英] Supply Polymorphic De-serialization/Serialization parameters to REST endpoint without changing POJOs
问题描述
我正在处理JAX-RS
应用程序,其中端点使用和产生JSON
类型数据.为此,我正在使用Jackson
.
I am working on a JAX-RS
application, where endpoints Consume and Produce JSON
type data. And I am using Jackson
for that purpose.
据我所知,处理Jackson
中多态行为的方法之一是在POJO上使用@JsonTypeInfo
和@JsonSubTypes
.
As I know one of the ways to handle Polymorphic behavior in Jackson
is to use @JsonTypeInfo
and @JsonSubTypes
on POJOs.
但是在我的情况下,POJO并不是代码的一部分,它们嵌入在JAR文件中,我无法对其进行编辑.
But in my case POJOs are not part of code, they're embedded in a JAR file and I can't edit them.
有什么方法可以在没有POJO注释的情况下在外部将此信息指定为Jackson
吗?
Is there any way where I can specify this info to Jackson
externally without POJO annotations ?
请为我指出正确的方向,前面已经讨论过.
Please point me to the right direction of this has already been discussed earlier.
推荐答案
有什么办法可以在没有POJO注释的情况下向外部Jackson指定此信息?
Is there any way where I can specify this info to Jackson externally without POJO annotations?
如果考虑使用混合注释,
使用注释仍然是一种有效的方法.
Using annotations is still a valid approach if you consider mix-in annotations.
When modifying the source code is not an option, you can use mix-in annotations to add Jackson annotations to a bean. You can think of it as kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.
首先定义一个混合注释接口或类:
First define a mix-in annotation interface or class:
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "class")
public interface FooMixIn {
}
然后配置ObjectMapper
以将定义的接口用作POJO的混合项:
Then configure ObjectMapper
to use the defined interface as a mix-in for your POJO:
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixIn.class);
可以混入Jackson识别的所有注释集.有关更多详细信息,请查看Jackson 文档.
All annotation sets that Jackson recognizes can be mixed in. For more details, have a look at the Jackson documentation.
这篇关于在不更改POJO的情况下向REST端点提供多态反序列化/序列化参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!