HttpMessageConverter是一个消息转换工具,有两方面的功能:
1.将服务端返回的对象序列化成json字符串
2.将前端传过来的json字符串反序列化成java对象
所有的json生成都离不开相关的HttpMessageConverter。SpringMVC自动配置了Jackson和Gson的HttpMessageConverter,SpringBoot对此做了自动化配置:
1.Jackson的自动化配置类
方式一:org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnBean(ObjectMapper.class)
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson", matchIfMissing = true)
static class MappingJackson2HttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class,
ignoredType = {
"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
"org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
return new MappingJackson2HttpMessageConverter(objectMapper);
}
}
方式二:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
}
2.Gson的自动化配置类
org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(Gson.class)
@Conditional(PreferGsonOrJacksonAndJsonbUnavailableCondition.class)
static class GsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean
GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
1.使用@JsonFormat注解
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
劣势:对每个实体类中的日期字段都需要添加此注解
2.提供MappingJackson2HttpMessageConverter类
在配置类中提供MappingJackson2HttpMessageConverter类,使用ObjectMapper 做全局的日期字段格式化(或者配置其他属性)。
@Configuration
public class WebMVCConfig {
@Bean
MappingJackson2HttpMessageConverter httpMessageConverter(){
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper om = new ObjectMapper();
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converter.setObjectMapper(om);
return converter;
}
}
此类会代替SpringBoot默认的json解析方案。事实上,此类中起作用的是ObjectMapper 类,因此也可直接配置此类。
3.提供ObjectMapper 类
在配置类中提供ObjectMapper 类。
@Configuration
public class WebMVCConfig {
@Bean
ObjectMapper om(){
ObjectMapper om = new ObjectMapper();
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
return om;
}
}