Jackson objectMapper使用多个配置

时间:2015-03-26 15:32:54

标签: jackson fasterxml

我有2个班级:A班,其中包含B班。 我需要将json解组为A类类型 - 但我需要A类具有一组反序列化功能,而B类需要具有不同的集合。 可能吗? 这样做最好的方法是什么? THX!

2 个答案:

答案 0 :(得分:0)

实际上,如果您想在每次通话的基础上更改SerializationFeatureDeserializationFeature,您不希望在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的构造很昂贵,并且实例绝对需要重复使用,ObjectReaderObjectWriter的构造很便宜并且意味着要按照每次读取/ - 写作基础。因此,虽然它们可以被重用(实例是完全线程安全的,不可变的)但并不一定需要它。

答案 1 :(得分:0)

最终我通过为内部类型定义自己的反序列化器并在内部定义自己的新静态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扩展JsonDeserializer {     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;
}

}