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,也可以在启动时配置

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

测试

在实体中添加@JSONField看是否序列化

@JSONField(serialize = false)

如果不序列化说明集成fastjson成功

方法二

配置在App.java 中

@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);
}

测试方法同上

猜你喜欢

转载自my.oschina.net/u/159221/blog/1621986