spring-boot 使用fastjson序列化對象

spring-boot 使用fastjson序列化對象

方法一

添加配置

//@SpringBootApplication
public class FastJsonAdapter extends WebMvcConfigurerAdapter {

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);

		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		fastConverter.setFastJsonConfig(fastJsonConfig);

		converters.add(fastConverter);
	}

}

可使用@SpringBootApplication,也能夠在啓動時配置java

@SpringBootApplication
public class App {
	public static void main(String[] args) {
		Class<?>[] c = {App.class,FastJsonAdapter.class};
		SpringApplication.run(c, args);
	}
}

測試

在實體中添加@JSONField看是否序列化spring

@JSONField(serialize = false)

若是不序列化說明集成fastjson成功json

方法二

配置在App.java 中ide

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
   FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
   FastJsonConfig fastJsonConfig = new FastJsonConfig();
   fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
   fastConverter.setFastJsonConfig(fastJsonConfig);
   HttpMessageConverter<?> converter = fastConverter;
   return new HttpMessageConverters(converter);
}

測試方法同上spring-boot

相關文章
相關標籤/搜索