为了统一转换json报文中的null字段为空字符串,集成了fastjson进行统一转换。
一、gradle引入jar
dependencies {
compile('org.springframework.boot:spring-boot-starter-undertow')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-eureka')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.cloud:spring-cloud-starter-sleuth')
compile('org.springframework.boot:spring-boot-starter-data-redis')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('com.github.pagehelper:pagehelper:4.1.0')
compile('com.alibaba:druid:1.0.18')
compile('com.alibaba:fastjson:1.2.38')
compile files('extlib/ojdbc6.jar')
compile files('extlib/mybatis-3.4.4.jar')
compile files('extlib/mybatis-spring-1.3.1.jar')
compile files('extlib/mybatis-spring-boot-autoconfigure-1.3.0.jar')
compile files('extlib/mybatis-spring-boot-starter-1.3.0.jar')
compile files('extlib/jsqlparser-0.9.4.jar')
runtime('org.springframework.boot:spring-boot-devtools')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
二、写个配置类
import java.nio.charset.Charset;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configuration
public class MvcConfig {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
// 输出空置字段
SerializerFeature.WriteMapNullValue,
// list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullListAsEmpty,
// 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullNumberAsZero,
// Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullBooleanAsFalse,
// 字符类型字段如果为null,输出为"",而不是null
SerializerFeature.WriteNullStringAsEmpty);
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastJsonConfig.setDateFormat("yyyy-MM-dd hh:mm:ss");
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
三、配置文件
在application.yml配置如下:
server:
port: ${PORT:8083}
context-path: /testdemo
eureka:
instance:
preferIpAddress: true
client:
registerWithEureka: true
fetchRegistry: true
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/**/*.xml
spring:
http:
encoding:
force: true
converters:
preferred-json-mapper: fastjson