springboot集成fastjson

大城市里の小女人 提交于 2020-11-08 05:30:12
@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    /**
     * fastjson configuration
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
        config.setSerializeFilters((ValueFilter) (object, name, value) -> {
            // 针对map类型value为null时输出""
            if (Objects.isNull(value)) {
                return "";
            }
            // 数字类型转字符串
            if (value instanceof Number) {
                return value.toString();
            }
            return value;
        });
        ArrayList<MediaType> mediaTypes = Lists.newArrayList();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.TEXT_PLAIN);
        converter.setSupportedMediaTypes(mediaTypes);
        converter.setFastJsonConfig(config);
        // 自定义序列化
        config.getSerializeConfig().put(Response.class, new ResponseSerializer(config));
        converters.add(converter);
    }
}

自定义序列化实现ObjectSerializer 接口

    public static class ResponseSerializer implements ObjectSerializer {
        private final FastJsonConfig fastJsonConfig;

        public ResponseSerializer(FastJsonConfig fastJsonConfig) {
            this.fastJsonConfig = fastJsonConfig;
        }

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
            SerializeWriter out = serializer.getWriter();
            Response response = (Response) object;
            out.write(JSON.toJSONString(response.body, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializeFilters(), fastJsonConfig.getSerializerFeatures()));
        }
    }

jsonp注解支持

fastjson已经内置了一个ResponseBodyAdvice接口的实现JSONPResponseBodyAdvice 我们只需要配置这个Bean就行了

@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    /**
     * use {@link ResponseJSONP}
     * controller return jsonp data
     */
    @Bean
    public ResponseBodyAdvice fastJsonpResponseBodyAdvice() {
        return new JSONPResponseBodyAdvice();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!