1. 程式人生 > >springboot新增fastjson第三方json解析工具方法(預設jackjson)

springboot新增fastjson第三方json解析工具方法(預設jackjson)

pom.xml新增配置資訊
父級標籤為dependencies

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.15</version>
</dependency>

1.App.class類繼承WebMvcConfigurerAdapter類
重寫configureMessageConverters方法

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		//定義一個convert 轉換訊息物件
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //配置fastjson 比如是否需要格式化返回的json資料
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        //向Converter新增配置資訊
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //將converter新增至converters
    	converters.add(fastConverter);
	}

2.直接在App.class中注入bean

	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		//定義一個Converter訊息轉換物件
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		//新增fastjson配置資訊
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		//將配置資訊新增至fastConverter
		fastConverter.setFastJsonConfig(fastJsonConfig);
		//將converter新增至converters中
		HttpMessageConverter<?> converter = fastConverter;
		return new HttpMessageConverters(converter);
	}

即可新增第三方json解析工具成功
實體類中 屬性值便可用@JSONField註解進行格式設定
如時間設定

@JSONField(format="yyyy-MM-dd HH:mm")
private Date time;

ending