- 在spring-boot-stater-web的依赖中排除jackson的依赖
<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>
- 引入Gson依赖
<!--引入Gson依赖-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
- 此外,我们还需要对gson进行一些自定配置
- 时间转换格式
- 过滤protected修饰的属性
- 。。。。。。
- 自定义GsonHttpMessageConverter,完成Gson自定义配置。
package com.nubipan.spring.boot.demo.conf;
/*
*@author nubipan
*@packageName com.nubipan.spring.boot.demo.conf
*@className GsonConfiguration
*@description:
*@date 2020/10/8 22:36
*/
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 GsonConfiguration {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter(){
//Spring提供了Gson的转换器对象
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
//创建Gson的构建器,通过构建器设置Gson的相关设置
GsonBuilder gsonBuilder = new GsonBuilder();
//设置Gson转化时间的格式
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
//Gson解析时,它将会过滤被protected修饰的属性
gsonBuilder.excludeFieldsWithModifiers(Modifier.PROTECTED);
//通过构建器创建Gson对象
Gson gson = gsonBuilder.create();
//将设置好的Gson对象,传递给转化器
converter.setGson(gson);
return converter;
}
}
基本的用法,做个笔记,避免日后要用忘记了,不喜勿喷会话😂😂😂
这篇博客介绍了如何在Spring Boot项目中弃用Jackson,改用Gson进行Json转换。内容包括排除Jackson依赖,引入Gson,配置Gson的时间格式和过滤protected属性,以及自定义GsonHttpMessageConverter以满足个性化需求。

2123

被折叠的 条评论
为什么被折叠?



