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 依赖(可选)
(2) 使用 Gson
配置 HttpMessageConverter
@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List
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 会启动失败