2019独角兽企业重金招聘Python工程师标准>>>
spring默认支持的是jackson2的json解析器.现在大部分人都习惯了fastJson的解析器.现在简单的说下如何配置json解析器
jackson2
配置如下:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
//JackSon 配置
@Override
public void configureMessageConverters(List> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
ObjectMapper objectMapper = builder.build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// 忽略 transient 修饰的属性
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
super.configureMessageConverters(converters);
}
}
可以使用@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")来格式化Date数据的输出. 默认日期是0时区的.早上8点会成为早上0点 对于@Transient注解是支持的,不会输出该注解修饰的字段
fastjson
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteEnumUsingToString,SerializerFeature.PrettyFormat,
//禁止循环引用,否则会出现 {"$ref":"$.data.giveAuthorList[0].goods"}
SerializerFeature.DisableCircularReferenceDetect,
//全局date 默认输出格式为"yyyy-MM-dd HH:mm:ss" 可通过修改com.alibaba.fastjson.Json.DEFFAULT_DATE_FORMAT设置
SerializerFeature.WriteDateUseDateFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}
该配置支持1.2.10以后的版本,如果有问题,请升级fastjson的版本. 可以使用@JSONField来配置序列化的属性
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
对于@Transient注解是不支持的,还是会输出该注解修饰的字段;
fastJsonConfig.setSerializerFeatures(SerializerFeature... serializerFeatures),这个方法配置序列化的特性.可传入多个特性.之前只有一个SerializerFeature.PrettyFormat,所以字段值为空就无法输出该字段. 2月5号发现后添加了一些处理空值的特性,和
- SerializerFeature.WriteEnumUsingToString 处理枚举,输出toString().
- SerializerFeature.WriteDateUseDateFormat 处理date类型数据,开始全局默认转化,默认输出格式为"yyyy-MM-dd HH:mm:ss" 可通过修改com.alibaba.fastjson.Json.DEFFAULT_DATE_FORMAT设置