使用fastjson作为springboot的默认json解析, 原来使用的是jackson
1, 引入依赖
<dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency>
注意: FastJsonHttpMessageConverter4支持4.2以上版本
FastJsonHttpMessageConverter,支持4.2以下的版本
第一种方法:
(1)启动类继承extends WebMvcConfigurerAdapter
(2)覆盖方法configureMessageConverters
@SpringBootApplication public class ApiCoreApp extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters);
// 定义一个convert转换消息对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 添加fastjosn配置信息, 比如是否格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat );
// convert中添加配置 fastConverter.setFastJsonConfig(fastJsonConfig); // 添加到convert中 converters.add(fastConverter); } }
第二种方法:
(1)在App.java启动类中,注入Bean : HttpMessageConverters
package com.iwhere; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @RestController @SpringBootApplication public class App {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullStringAsEmpty);
fastConverter.setFastJsonConfig(fastJsonConfig);
// 返回HttpMessageConvert对象
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
测试方法:
在实体类中使用@JSONField(Serialize=false) 字段不返回即是成功
在data字段上添加
@JSONFIled(format="yyyy-mm-dd HH:mm:ss")
既可以实现自动转化
本博客来源: http://412887952-qq-com.iteye.com/blog/2315202