当前位置: 代码迷 >> 综合 >> spring boot2 修改默认json解析器Jackson为fastjson
  详细解决方案

spring boot2 修改默认json解析器Jackson为fastjson

热度:36   发布时间:2023-10-17 16:58:14.0

为什么要修改,转化出错,某些情况下转为后的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的实例中并返回converterGson 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;}}

 

  相关解决方案