修改spring mvc的默认HttpMessageConverter属性

spring mvc 中的http消息转换示意图

spring mvck中默认使用了jackson提供的HttpMessageConverter来进行对象的json序列化/反序列化,可以按下面的方法修改其默认属性:

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {        WebMvcUtils.normalizeMappingJackson2HttpMessageConverter(converters);
}

WebMvcUtils实现如下:

/**
 * Spring web mvc 工具类
 */
public class WebMvcUtils {

    private WebMvcUtils() {

    }

    /**
     * 找到http message converters中的jackson converter
     *
     * @param converters
     * @return
     */
    public static MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> httpMessageConverter : converters) {
            if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {
                return (MappingJackson2HttpMessageConverter) httpMessageConverter;
            }
        }
        return null;
    }

    /**
     * 对jackson http message converter进行统一规格化
     *
     * @param converters
     */
    public static void normalizeMappingJackson2HttpMessageConverter(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = getMappingJackson2HttpMessageConverter(converters);
        ObjectMapper objectMapper;
        if (ObjectUtil.isNull(mappingJackson2HttpMessageConverter)) {
            mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
            objectMapper = ObjectMapperUtil.getObjectMapper();
            mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
            converters.add(mappingJackson2HttpMessageConverter);
        } else {
            objectMapper = mappingJackson2HttpMessageConverter.getObjectMapper();
            ObjectMapperUtil.normalize(objectMapper);
        }
    }
}

ObjectMapperUtil的normalize方法实现如下:

    public static void normalize(ObjectMapper objectMapper) {
        // 不输出空值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 不输出空白
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        // 反序列化忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 使用 ISO 8601 时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
        objectMapper.setDateFormat(sdf);
    }

通过对HttpMessageConverter中的ObjectMapper的属性设置,可以控制其Json序列化的输出格式。

最后编辑于:2019/9/2作者: 编程小战

我不入地狱,谁入地狱?

评论已关闭