spring内置的消息转换器
@ResponseBody可以把java对象转换成json
spring内置了很多消息转换器,当我们没有定义消息转换器时就会使用默认的消息转换器。
在直接返回json对象的时候,如果包含date类型的对象,默认转换成json的时候是转换成long型的格式,不是我们常用的"yyyy-MM-dd HH:mm:ss"格式。
这时候需要做一个转换,比较喜欢下面的方式,直接在实体类中注解:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
其中JsonFormat为 com.fasterxml.jackson.annotation.JsonFormat;
不指定时区的话时间会出错
自定义消息转换器
在启动类上或者@Configuration的类中添加如下代码就可以了
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定义一个convert转换消息的对象;
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//2:添加fastJson的配置信息;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//处理空值,让其转换为null
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
//3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
return new HttpMessageConverters(converter);
}
其中FastJson日期的处理要加上
@JSONField(format = "yyyy-MM-dd HH:mm:ss")