SpringBoot JSON库默认采用 JACKSON。
1、Jackson
@JsonComponent
public class JsonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
/**
* 可配置项:
* 1.Include.Include.ALWAYS : 默认
* 2.Include.NON_DEFAULT : 默认值不序列化
* 3.Include.NON_EMPTY : 属性为 空("") 或者为 NULL 都不序列化
* 4.Include.NON_NULL : 属性为NULL 不序列化
**/
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
/**
* 序列化时,将所有的long变成string
*/
SimpleModule module = new SimpleModule();
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(module);
return objectMapper;
}
}
参考:https://blog.csdn.net/nicolas12/article/details/83342151
2、FastJson
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- json库统一使用fastjson -->
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 导入 fastjson 依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 利用fastJson替换掉jackson,且解决中文乱码问题
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNonStringKeyAsString,
SerializerFeature.BrowserCompatible);
//解决Long转json精度丢失的问题
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class, ToStringSerializer.instance);
serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(serializeConfig);
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}