自定义Jackson Serializer for Wrapper Object [英] Custom Jackson Serializer for Wrapper Object
问题描述
我有提供者界面
interface IProvider<T> {
T locate();
}
以及包含IProvider类型字段的类(可以是其他类型的其他类型)字段)。
and a class containing a field of type IProvider (can be another type for other fields).
class MyObject {
MyLocator<String> field;
}
我需要使用Jackson 1.7将MyObject的实例序列化为JSON。输出必须与MyObject.field是一个String(即没有ILocator的引用)相同。
I need to serialize instances of MyObject to JSON using Jackson 1.7. The output must be the same as if MyObject.field had been a String (i.e. no reference to ILocator).
我无法弄清楚如何构建自定义序列化程序需要实现这一目标。以下是我尝试用于此任务的结构:
I can't figure out how to build the custom serializer required to achieve this. Here is the structure I am trying to use for this task:
class MyLocatorSerializer extends SerializerBase<MyLocator<?>> {
public MyLocatorSerializer() {
super(MyLocator.class, false);
}
@Override
public void serialize(MyLocator<?> a_value, JsonGenerator a_jgen,
SerializerProvider a_provider) throws IOException, JsonGenerationException {
// Insert code here to serialize a_value.locate(), whatever its type
}
@Override
public JsonNode getSchema(SerializerProvider a_provider, Type a_typeHint)
throws JsonMappingException {
// What should I return here? I can't find documentation regarding the different schema types...
}
}
自定义序列化程序将使用
The custom serializer would be registered using
SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addSerializer(new MyLocatorSerializer());
objectMapper.registerModule(module);
推荐答案
在评论之后使用混合注释的另一个答案Staxman。
Another answer using mix-in annotations following the comment from Staxman.
static class JacksonCustomModule extends SimpleModule {
public JacksonCustomModule() {
super("JacksonCustomModule", new Version(1, 0, 0, null));
}
@Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(IProvider.class, IProviderMixIn.class);
super.setupModule(context);
}
interface IProviderMixIn<T> {
@JsonValue
T locate();
}
}
激活模块:
objectMapper.registerModule(new JacksonCustomModule());
这篇关于自定义Jackson Serializer for Wrapper Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!