Spring MVC中使用fastjson
在Spring MVC中,请求与响应根据HttpMessageConverter的定义来编解码,请求或者响应根据SupportedMediaTypes来确定使用哪一个HttpMessageConverter。
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {
/**
* 使用fastJson作为json序列化工具
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//删除自带的json序列化
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
fastJsonHttpMessageConverter.setDefaultCharset(Charset.forName("utf-8"));
//*+json 兼容actuator的请求
fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("application", "*+json"),
MediaType.APPLICATION_JSON_UTF8));
converters.add(fastJsonHttpMessageConverter);
}
}
Spring Cloud Gateway使用fastjson
Spring Cloud Gateway基于Spring WebFlux开发,在WebFlux中没有WebMvcConfigurer,去除默认的json工具会出现各种问题,但是可以修改默认json工具的编解码
@Configuration
public class JsonConfiguration {
/**
* 自定义json编码器
*/
@Bean
public CodecCustomizer jsonCodecCustomizer() {
return configurer -> configurer.defaultCodecs().jackson2JsonEncoder(new JsonEncoder());
}
/**
* json编码器
*/
public static class JsonEncoder implements Encoder<Object> {
@Override
public boolean canEncode(ResolvableType elementType, MimeType mimeType) {
return true;
}
@Override
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType,
MimeType mimeType, Map<String, Object> hints) {
if (inputStream instanceof Mono) {
return Mono.from(inputStream)
.map(value -> encodeValue(value, bufferFactory))
.flux();
}
return null;
}
@Override
public List<MimeType> getEncodableMimeTypes() {
return Collections.singletonList(MimeTypeUtils.APPLICATION_JSON);
}
/**
* 处理数据
*/
private DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory) {
DataBuffer buffer = bufferFactory.allocateBuffer();
byte[] bytes = JSON.toJSONBytes(value, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
buffer.write(bytes);
return buffer;
}
}
}
网友评论