最近公司框架统一升级到了 SpringCloud 2.0 轻车熟路的配置了 FastJson 但是并没有生效 记录一下解决过程
FastJson 没生效
是由于 Jackson2 优先转换导致的
直接贴上新配置 ( 本来这个是继承接口的 但是Java8有默认实现 所以简化了)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| package com.sixi.micro.common.config;
import java.nio.charset.Charset; import java.util.List;
import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.sixi.micro.common.convert.converter.CustomFastJsonMessageConverter;
@Configuration public class MvcConfigurer implements WebMvcConfigurer {
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter); converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new CustomFastJsonMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.DisableCircularReferenceDetect); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastJsonHttpMessageConverter); } }
|
ContentType 为 / 的时候报错
由于 SpringBoot 2.0 为了安全 禁止了 / 的类型 所以 转换的时候替换一下就好了 继承 重写 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package com.sixi.micro.common.convert.converter;
import java.io.IOException; import java.lang.reflect.Type;
import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageNotWritableException;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
public class CustomFastJsonMessageConverter extends FastJsonHttpMessageConverter { @Override public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (contentType.isWildcardType() || contentType.isWildcardSubtype() || contentType == MediaType.APPLICATION_OCTET_STREAM) { contentType = MediaType.APPLICATION_JSON_UTF8; } super.write(o, type, contentType, outputMessage); } }
|