fastjson简介
fastjson是阿里巴巴的一个开源的JSON解析框架,fastjosn是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象.
fastjson可以很好的集成到Spring Boot中.当然,fastjson继承完成之后并不能立马使用,需要提供响应的HttpMessageConverter后才能使用.
去除JSON,引入fastjson依赖
Json是目前主流的前后端数据传输方式,Spring MVC中使用消息转换器HttpMessageConverter对JSON的转换提供了很好的支持.
对于Spring Boot相关配置做了进一步的简化.当我们创建一个Spring Boot项目后.添加Web依赖,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<dependency>
这个依赖默认使用了jackson-databind作为JSON处理器,此时不需要添加就能返回一段JSON.
首先除去jackson-databind依赖,引入fastjson依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
配置fastjson的HttpMessageConverter
代码如下:
package com.myti.common.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.charset.Charset;
@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd");
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
// 是否输出类名,是否输出value为null的数据,生产JSON格式化,空集合输出【】而非null,空字符串输出”“而非null等配置
fastJsonConfig.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
return fastJsonHttpMessageConverter;
}
}
配置完成后,还需要配置下响应编码,否则返回的JSON中文会乱码.在application.proerties中添加如下配置:
server.servlet.encoding.force-response=true
即可