MappingJackson2HttpMessageConverter与Jackson2ObjectMapperBuilder

时间:2016-02-25 12:49:02

标签: json spring jackson

谁能告诉我这些物品之间有什么区别?当我使用第一个弹簧时,弹簧的作用与第二弹簧不同,尽管它们几乎配置相同。

两者都在我的WebMvcConfigurerAdapter中配置。当我应该使用哪一个来配置JSON-Serialization和JSON-Deserialization?

我的代码:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.setSerializationInclusion(Include.ALWAYS);
    jsonConverter.setObjectMapper(objectMapper);
    return jsonConverter;
}



@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        builder.serializationInclusion(Include.ALWAYS);
        builder.failOnEmptyBeans(false);
        builder.failOnUnknownProperties(false);
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }

1 个答案:

答案 0 :(得分:2)

您需要定义MappingJackson2HttpMessageConverter才能序列化和反序列化您的JSON输入。 Jackson使用类ObjectMapper将JSON转换为Java对象,反之亦然,因此Jackson2ObjectMapperBuilder只是一个方便的类,它使用Builder模式为您构建ObjectMapper,后来可以将其注入转换器