SpringBoot 使用 Gson 序列化(禁用 Jackson)

2026-07-15 22:40:53   竞技场直播

1. SpringBoot 整合 Gson

Jackson is the preferred and default library.

Jackson

Auto-configuration for Jackson is provided and Jackson is part of spring-boot-starter-json. When Jackson is on the classpath an ObjectMapper bean is automatically configured. Several configuration properties are provided for customizing the configuration of the ObjectMapper.

Gson

Auto-configuration for Gson is provided. When Gson is on the classpath a Gson bean is automatically configured. Several spring.gson.* configuration properties are provided for customizing the configuration. To take more control, one or more GsonBuilderCustomizer beans can be used.

(1) 禁用 Jackson

去除 JacksonAutoConfiguration

@SpringBootApplication(exclude = {JacksonAutoConfiguration.class})

去除 Jackson 依赖(可选)

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-json

(2) 使用 Gson

com.google.code.gson

gson

2.8.6

配置 HttpMessageConverter

@Configuration

public class ApplicationConfig extends WebMvcConfigurerAdapter {

@Override

public void configureMessageConverters(List> converters) {

converters.add(customGsonHttpMessageConverter());

super.configureMessageConverters(converters);

}

private GsonHttpMessageConverter customGsonHttpMessageConverter() {

return new GsonHttpMessageConverter(new GsonBuilder().create());

}

}

或使用此方式(推荐)

@Configuration

public class GsonConfig {

@Bean

public GsonHttpMessageConverter customGsonHttpMessageConverter(Gson gson) {

return new GsonHttpMessageConverter(gson);

}

}

(3) 验证

至此,@ResponseBody 转化 Json 时使用的就是 GsonHttpMessageConverter

2. 整合 Swagger

SpringBoot 整合 Swagger3.0

Springfox 默认使用 Jackson 做序列化。若使用 Gson,则解析的 Json 格式会有误

@Configuration

public class GsonConfig {

@Bean

public Gson gson() {

return new GsonBuilder()

.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter())

.create();

}

@Bean

public GsonHttpMessageConverter customGsonHttpMessageConverter(Gson gson) {

return new GsonHttpMessageConverter(gson);

}

public class SpringfoxJsonToGsonAdapter implements JsonSerializer {

@Override

public JsonElement serialize(Json json, Type type, JsonSerializationContext jsonSerializationContext) {

return JsonParser.parseString(json.value());

}

}

}

注意:需引入 Jackson 包,否则 Swagger 会启动失败

诛仙3坐骑加成爆料,血脉激活/属性名称
后视镜被掰断了换一个多少钱?后视镜撞断了修理要多少钱