在Jackson中创建工厂JSON反序列化程序
我有一组接口,注释如下:在Jackson中创建工厂JSON反序列化程序,json,jackson,deserialization,Json,Jackson,Deserialization,我有一组接口,注释如下: @MyAnnotation(DefaultImplementation.class) interface SomeInterface { ... } 以及相应的实现 class DefaultImplementation implements SomeInterface { ... } 当ObjectMapper运行到类型为SomeInterface的字段时,我希望它将其反序列化,就像它是DefaultImplementation一样。也就是说,我希
@MyAnnotation(DefaultImplementation.class)
interface SomeInterface {
...
}
以及相应的实现
class DefaultImplementation implements SomeInterface {
...
}
当ObjectMapper运行到类型为SomeInterface
的字段时,我希望它将其反序列化,就像它是DefaultImplementation
一样。也就是说,我希望在反序列化过程中对以下逻辑进行编码:
if (staticTypeToDeserialize.isAnnotationPresent(MyAnnotation.class))
deserializeAs(type.getAnnotation(MyAnnotation.class).value());
else
fallBackOnRegularDeserialization();
我希望我能给你一个完整的答案。杰克逊可以通过混音来做到这一点。我不是这方面的专家,但我最近做了,所以。。。本质上,您将类型信息粘贴到JSON中,然后Jackson可以使用该类型信息以您想要的方式对其进行反序列化 因此,首先,您需要一个mixin类,它知道要序列化和反序列化的类型
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = MyString.class, name = "mystring"),
@JsonSubTypes.Type(value = MyEvent.class, name = "myevent") })
public abstract class PolymorphicMixIn {
}
在我的例子中,MyString和MyEvent类派生自同一个基类。所以我在杰克逊身上留下的一切都是那种类型的。假设基类是MyBaseClass
因此,在jackson课程中,您需要告诉对象映射器这一点
private ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixInAnnotations(MyBaseClass.class, PolymorphicMixIn.class);
差不多就是这样。现在,您可以调用objectMapper.writeValueAsString,它将编写Jackson并插入类型信息
要读取它,只需传入所需的类类型:
MyString outputString = objectMapper.readValue(argAsString, MyString.class);
我希望这足以让你达到你需要的地方 这难道不需要我用
@myannotatiton
为每个接口创建一个mixin吗?这是不可取的。我希望能够轻松地添加带有@MyAnnotation
注释的新接口。此外,这需要我修改JSON表示。这在我的设置中也是不可取的。这就是我认为我的反序列化程序需要某种形式的工厂的原因(即基于@MyAnnotation
注释动态创建反序列化程序的方法)