package com.xxxxxxxx.config; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.ToStringSerializer; 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.Charset; import java.util.ArrayList; import java.util.List; @Configuration public class FastjsonCovert { @Bean public HttpMessageConverters fastJsonHttpMessageCoverters() { FastJsonHttpMessageConverter fastCoverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); //修改配置返回内容的过滤 fastJsonConfig.setSerializerFeatures( // 格式化 SerializerFeature.PrettyFormat, // 可解决long精度丢失 但会有带来相应的中文问题 //SerializerFeature.BrowserCompatible, // 消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环) SerializerFeature.DisableCircularReferenceDetect, // 是否输出值为null的字段,默认为false SerializerFeature.WriteMapNullValue, // 字符类型字段如果为null,输出为"",而非null SerializerFeature.WriteNullStringAsEmpty, // List字段如果为null,输出为[],而非null SerializerFeature.WriteNullListAsEmpty ); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); // long精度问题 SerializeConfig serializeConfig = SerializeConfig.globalInstance; serializeConfig.put(Long.class, ToStringSerializer.instance); serializeConfig.put(Long.TYPE, ToStringSerializer.instance); // serializeConfig.put(LocalDateTime.class, LocalDateTimeSerializer.); //处理中文乱码问题 List<MediaType> mediaTypeList = new ArrayList<MediaType>(); mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8); mediaTypeList.add(new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"))); mediaTypeList.add(new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"))); mediaTypeList.add(new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("UTF-8"))); mediaTypeList.add(MediaType.MULTIPART_FORM_DATA); fastCoverter.setSupportedMediaTypes(mediaTypeList); //3、在convert中添加配置信息 fastCoverter.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastCoverter); } }