我有两个类:A类,其中包含B类。我需要将json解组为A类,但我需要A类具有一组反序列化特性,而类B具有一组不同的特性。有可能吗?最好的方法是什么?Thx!
实际上,如果您想在每次调用的基础上更改SerializationFeature
或DeserializationFeature
,您不希望使用ObjectMapper
中的方法,而是像这样构造ObjectReader
和/或ObjectWriter
:
static final ObjectMapper mapper = ...; // only create once, acts as factor
// later on
byte[] json = mapper.writer(SerializationFeature.INDENT_OUTPUT)
.without(SerializationFeature. WRAP_EXCEPTIONS)
.writeValueAsBytes(value);
MyType result = mapper.readerFor(MyType.class)
.with(DeserializationFeature.UNWRAP_ROOT_VALUE)
// and more 'with' or 'without' calls
readValue(json);
请注意,尽管ObjectMapper
的构造是昂贵的,并且实例绝对需要重用,但ObjectReader
和ObjectWriter
的构造是廉价的,并且意味着在每次读/写的基础上进行。因此,虽然它们可以重用(实例是完全线程安全的、不可变的),但不一定有太多需求。
最终,我为内部类型定义了自己的反序列化程序,并在内部定义了自己新的静态ObjectMapper来保存所需的配置,从而解决了这个问题。
public ObjectMapper MyObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper
.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()))
SimpleModule simpleModule = new SimpleModule("PostSurveyModule", Version.unknownVersion());
simpleModule.addDeserializer(MyInnerObject.class, new MyInnerObjectDeserializer());
objectMapper.registerModule(simpleModule);
return objectMapper;
}
public static class MyInnerObjectDeserializer extends JsonDeserializer<MyInnerObject> {
static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper
.setVisibilityChecker(objectMapper.getDeserializationConfig().getDefaultVisibilityChecker()
.withGetterVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY));
objectMapper.addMixInAnnotations(MyInnerObject.class, MyInnerObjectMixin.class); //some mixin to add
}
@Override
public MyInnerObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
MyInnerObject myInnerObject = objectMapper.readValue(jp, MyInnerObject.class);
return myInnerObject;
}
}