Springboot構成json処理方式

2115 ワード

1つ目:クラス継承の開始WebMvcConfigurerAdapter、上書き方法configureMessageConverters
@SpringBootApplication  //   spring boot            
public class AppStart extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(AppStart.class, args);
    }

    /**
     *     json fastjson
     */
    @Override
    public void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat, 
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullNumberAsZero, 
                SerializerFeature.WriteNullStringAsEmpty
            );
        //         
        List fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //     ,                   
        StringHttpMessageConverter smc = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        converters.add(smc);

        converters.add(fastConverter);
    }
}

2つ目:@Bean注入サードパーティのjson解析フレームワーク
@Bean//  @Bean  fastJsonHttpMessageConvert
public HttpMessageConverters fastJsonHttpMessageConverters(){
	//1.      Convert       
	FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
	//2.  fastjson     ,           json  
	FastJsonConfig fastJsonConfig=new FastJsonConfig();
	//SerializerFeature.WriteMapNullValue   null   
	fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
	//3. convert       
	fastConverter.setFastJsonConfig(fastJsonConfig);
	HttpMessageConverter> converter=fastConverter;
	return new HttpMessageConverters(converter);
}