在目前web开发中,JSON是主流的数据传输方式,在SpringMVC中使用消息转换器HttpMessageConverter对JSON的转换提供了很好的支持,在SpringBAoot中,对JSON转换做了进一步的简化。常用的JSON序列化方式主要有三种:
A、默认方式
B、fastjson(alibaba)
C、Gson(google)
首先说一下默认Json序列G化的方式,这种方式只要在实体类的字段上添加注解即可。以下为案例:
1、创建SpringBoot项目并在pom.xml文件中添加web依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hongke</groupId>
<artifactId>JsonApplication</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<description>this is json serialize demo</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
注:在web依赖中默认加入了jackson-databind作为JSON处理器,此时不在需要添加额外的JSON处理器。
2、创建实体类并添加序列化格式:
package com.hongke.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
/**
* @author chengjunyu
* @classname Goods
* @description TODO
* @date 2020/7/25 21:54
*/
@Data
@AllArgsConstructor
public class Goods {
private String name;
private String property;
@JsonIgnore
//输出时忽略该字段
private Double price;
@JsonFormat(pattern = "yyyy-MM-dd")
//以yyyy-MM-dd的格式输出时间字段
private Date createTime;
}
3、创建Controller层接口请求:
package com.hongke.controller;
import com.hongke.entity.Goods;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* @author chengjunyu
* @classname FoodController
* @description TODO
* @date 2020/7/25 21:56
*/
@RestController
@RequestMapping("/shop")
public class GoodsController {
@GetMapping("/getGoods")
public Goods getGoods() {
Goods goods = new Goods("蛋黄派", "面包", 18.5, new Date());
return goods;
}
}
4、创建启动类和application.properties文件:
JsonApplication.java:
package com.hongke;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author chengjunyu
* @classname JsonApplication
* @description TODO
* @date 2020/7/25 21:52
*/
@SpringBootApplication
public class JsonApplication {
public static void main(String[] args) {
SpringApplication.run(JsonApplication.class);
}
}
applicaton.properties:
server.port=9003
5、Postman发送请求到localhost:9003/shop/getGoods,结果如下:
通过返回的结果,可以看出,价格字段未被展示,制造时间只显示了年-月-日,由此,默认格式的JSON序列化完成。
说完了默认方式实现JSON序列化后,接下来看看怎么样使用fastjson进行JSON序列化输出,fastjson是alibaba开源的一个JSON解析框架,是目前JSON解析速度最快的开源框架。以下为案例:
1、修改默认JSON案例中的pom文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hongke</groupId>
<artifactId>JsonApplication</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<description>this is json serialize demo</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind:2.5.0</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
注:去除web依赖中jackson-databind依赖,增加alibaba的fastjson依赖;
2、配置fastjson的消息转换器HttpMessageConverter,代码如下:
MyFastJsonConfig.class
package com.hongke.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;
/**
* @author chengjunyu
* @classname MyFastJsonConfig
* @description TODO
* @date 2020/7/25 22:57
*/
@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter messageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//数据编码-UTF-8
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
//日期格式
fastJsonConfig.setDateFormat("yyyy-MM-dd");
fastJsonConfig.setSerializerFeatures(
//在生成的JSON中输出类名
SerializerFeature.WriteClassName,
//输出value为null的数据
SerializerFeature.WriteMapNullValue,
//空集合输出[]而不是null
SerializerFeature.WriteNullListAsEmpty,
//空字符串输出""而不是null
SerializerFeature.WriteNullStringAsEmpty,
//生成的json格式话
SerializerFeature.PrettyFormat
);
messageConverter.setFastJsonConfig(fastJsonConfig);
return messageConverter;
}
}
3、修改实体类,代码如下:
package com.hongke.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
/**
* @author chengjunyu
* @classname Food
* @description TODO
* @date 2020/7/25 21:54
*/
@Data
@AllArgsConstructor
public class Goods {
private String name;
private String property;
private Double price;
private Date createTime;
}
4、Postman发送请求到localhost:9003/shop/getGoods,结果如下:
此处输出的内容符合我们在MyFastJsonConfig中设定的格式,输出了类名,并以yyyy-MM-dd格式输出了时间,fastjson序列化由此完成。
以上内容为通过fastjson框架进行JSON序列化输出,接下来需要说的是最后一种方式,通过google的Gson框架进行JSON序列化输出。使用Gson的方式和fastjson的方式大同小异,具体区别直接看以下代码:
1、修改pom文件为如下内容:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hongke</groupId>
<artifactId>JsonApplication</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<description>this is json serialize demo</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind:2.5.0</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
2、添加Gson的消息转换配置,代码如下:
package com.hongke.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.lang.reflect.Modifier;
/**
* @author chengjunyu
* @classname MyGsonConfig
* @description TODO
* @date 2020/7/25 23:15
*/
@Configuration
public class MyGsonConfig {
@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter() {
GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
GsonBuilder gsonBuilder = new GsonBuilder();
//以年-月-日 时:分的形式输出时间
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm");
//用protected修饰的字段不输出
gsonBuilder.excludeFieldsWithModifiers(Modifier.PROTECTED);
Gson gson = gsonBuilder.create();
messageConverter.setGson(gson);
return messageConverter;
}
}
3、修改实体类,代码如下:
package com.hongke.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
/**
* @author chengjunyu
* @classname Food
* @description TODO
* @date 2020/7/25 21:54
*/
@Data
@AllArgsConstructor
public class Goods {
private String name;
protected String property;
private Double price;
private Date createTime;
}
此处将property字段的修饰词改为protected,按照上方Gson转换的配置来看,应该不会再输出该字段的内容了。
4、Postman发送请求到localhost:9003/shop/getGoods,结果如下:
由输出结果可见,返回的结果完全符合之前的预期,因此使用Gson对JSON进行序列化输出也已经完成。