1、spring boot默认使用jackson对json序列化和发序列化
可在配置文件中增加默认的时间格式化方式:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; public class MrType { @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") private Date createdDate; }
2、使用fastjson对json数据序列化和发序列化
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.converter.HttpMessageConverter;
@SpringBootApplication
public class MonitorRedbagMqApplication {
public static void main(String[] args) {
SpringApplication.run(MonitorRedbagMqApplication.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
//FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//FastJsonConfig fastJsonConfig = new FastJsonConfig();
//fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//fastConverter.setFastJsonConfig(fastJsonConfig);
//HttpMessageConverter<?> converter = fastConverter;
//return new HttpMessageConverters(converter);
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//过滤并修改配置返回内容
fastJsonConfig.setSerializerFeatures(
//List字段如果为null,输出为[],而非null
SerializerFeature.WriteNullListAsEmpty,
//字符类型字段如果为null,输出为"",而非null
SerializerFeature.WriteNullStringAsEmpty,
//Boolean字段如果为null,输出为false,而非null
//SerializerFeature.WriteNullBooleanAsFalse,
//消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
SerializerFeature.DisableCircularReferenceDetect,
//是否输出值为null的字段,默认为false。
SerializerFeature.WriteMapNullValue
);
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonConverter.setSupportedMediaTypes(fastMediaTypes);
fastJsonConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastJsonConverter;
return new HttpMessageConverters(converter);
}
}
3、测试Java对象
public class MonitorRedbagDto implements Serializable {
private static final long serialVersionUID = -1600920246142453543L;
// 红包ID
private Integer redbagId;
// 用户ID
private Long userId;
// 发放时间
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date sendTime;
// setter getter方法
}
如果不用fastjson序列化,返回:
{
"redbagId": null,
"userId": 16,
"sendTime": "2018-03-06T12:04:15.483+0000"
}
使用fastjson序列化,返回:
{
"userId": 16,
"sendTime": "2018-03-06 12:04:15"
}