我有一个在.jar中的课程,我无法修改。
它在类上有一个@JsonSerialize()
注释。
@JsonSerialize(using = SomeClassSerializer.class)
@JsonDeserialize(using = SomceClassDeserializer.class)
public class SomeClass { /* ommitted */ }
现在,我需要在此类上运行自定义序列化程序,以输出完全不同的JSON。
以下是我的尝试:
final SomeClass sc = new SomeClass();
// setup ommitted
final ObjectMapper m = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(SomeClass.class, new CustomClassSerializer());
m.registerModule(module);
m.enable(SerializationFeature.INDENT_OUTPUT);
m.writer().writeValue(System.out, sc);
问题是我得到默认带注释的SomeClassSerializer
输出而不是CustomClassSerializer
输出。
ObjectMapper
忽略注释?答案 0 :(得分:4)
您可以使用the Jackson mixin annotations覆盖原始类序列化程序。这是一个例子:
public class JacksonMixInOverride {
public static class BeanSerializer extends JsonSerializer<Bean> {
@Override
public void serialize(Bean value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeString("normal");
}
}
public static class CustomBeanSerializer extends JsonSerializer<Bean> {
@Override
public void serialize(Bean value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
jgen.writeString("custom");
}
}
@JsonSerialize(using = BeanSerializer.class)
public static class Bean {
}
@JsonSerialize(using = CustomBeanSerializer.class)
public static interface BeanMixIn {
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Bean.class, BeanMixIn.class);
System.out.println(mapper.writeValueAsString(new Bean()));
}
}
输出:
"custom"
答案 1 :(得分:3)
final ObjectMapper m = new ObjectMapper();
m.disable(MapperFeature.USE_ANNOTATIONS);
经过大量挖掘JavaDocs后,我发现了这个解决方案,这似乎是最惯用的方法。