为什么要修改,转化出错,某些情况下转为后的json为空
引入依赖
maven
<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.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
gradle
implementation ('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'com.fasterxml.jackson.core', module: 'jackson-databind'
}
implementation 'com.google.code.gson:gson:2.8.6'
代码
package com.futve.example.configure;
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(){
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
//设置Gson解析时日期的格式
builder.setDateFormat("yyyy-MM-dd");
//设置Gson解析时修饰符为protected的字段被过滤掉
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
//创建Gson对象放入GsonHttpMessageConverter的实例中并返回converter
Gson gson = builder.create();
converter.setGson(gson);
return converter;
}
}
转换工具
package com.futve.example.tool;
import com.google.gson.Gson;
/**
* 基于Gson封装的jsonUtil
*
* @author chenye
* @date 2020-0828
* implementation 'com.google.code.gson:gson:2.8.6'
*/
public class GsonUtil {
private static Gson gson = null;
static {
if (gson == null) {
gson = new Gson();
}
}
private GsonUtil() {
}
/**
* 对象转成json
*/
public static String objectToJson(Object object) {
String json = null;
if (gson != null) {
json = gson.toJson(object);
}
return json;
}
/**
* Json转成对象
*/
public static <T> T gsonToBean(String json, Class<T> cls) {
T t = null;
if (gson != null) {
t = gson.fromJson(json, cls);
}
return t;
}
}