48 lines
2.0 KiB
Java
48 lines
2.0 KiB
Java
|
|
package com.upchina.common.config;
|
|||
|
|
|
|||
|
|
import com.alibaba.fastjson.parser.ParserConfig;
|
|||
|
|
import com.alibaba.fastjson.serializer.SerializerFeature;
|
|||
|
|
import com.alibaba.fastjson.support.config.FastJsonConfig;
|
|||
|
|
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
|
|||
|
|
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
|||
|
|
import org.springframework.context.annotation.Bean;
|
|||
|
|
import org.springframework.context.annotation.Configuration;
|
|||
|
|
import org.springframework.http.MediaType;
|
|||
|
|
|
|||
|
|
import java.nio.charset.StandardCharsets;
|
|||
|
|
import java.util.ArrayList;
|
|||
|
|
import java.util.List;
|
|||
|
|
|
|||
|
|
@Configuration
|
|||
|
|
public class JsonConfig {
|
|||
|
|
|
|||
|
|
static {
|
|||
|
|
ParserConfig.getGlobalInstance().setSafeMode(true);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
@Bean // 使用@Bean注入fastJsonHttpMessageConvert
|
|||
|
|
public HttpMessageConverters fastJsonHttpMessageConverters() {
|
|||
|
|
// 1.需要定义一个Convert转换消息的对象
|
|||
|
|
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
|
|||
|
|
|
|||
|
|
// 2.添加fastjson的配置信息,比如是否要格式化返回的json数据
|
|||
|
|
FastJsonConfig fastJsonConfig = new FastJsonConfig();
|
|||
|
|
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段
|
|||
|
|
SerializerFeature.WriteNullListAsEmpty, // 将Collection类型字段的字段空值输出为[]
|
|||
|
|
// SerializerFeature.WriteNullNumberAsZero, // 将数值类型字段的空值输出为0
|
|||
|
|
SerializerFeature.DisableCircularReferenceDetect, // 禁用循环引用
|
|||
|
|
SerializerFeature.WriteDateUseDateFormat); //时间格式化
|
|||
|
|
|
|||
|
|
// 中文乱码解决方案
|
|||
|
|
List<MediaType> mediaTypes = new ArrayList<>();
|
|||
|
|
mediaTypes.add(new MediaType("application", "json", StandardCharsets.UTF_8));//设定json格式且编码为UTF-8
|
|||
|
|
fastConverter.setSupportedMediaTypes(mediaTypes);
|
|||
|
|
|
|||
|
|
// 3.在convert中添加配置信息
|
|||
|
|
fastConverter.setFastJsonConfig(fastJsonConfig);
|
|||
|
|
|
|||
|
|
return new HttpMessageConverters(fastConverter);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|