【第04章】Spring Boot整合Web开发 - 配置自定义JSON转换器
程序员文章站
2022-05-08 10:55:45
...
- Spring Boot使用默认的转换器是
jackson-databind
,如果我们使用自定义转换器时,我们需要去除默认的jackson-databind,比如我们使用Gson作为转换器时我们在pom.xml中添加如下配置:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
<!-- 配置json转换器先去除默认的jackson-databind -->
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加自定义json转换器 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
由于Gson进行转换时,如果想对日期数据进行格式化,那么还需要开发者自定义HttpMessageConverter。自定义HttpMessageConverter可以通过如下方式:
package cn.youxin.chapter03;
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;
@Configuration
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter() {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
//格式化日期格式
builder.setDateFormat("yyyy-MM-dd");
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
Gson gson = builder.create();
converter.setGson(gson);
return converter;
}
}