Loading

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

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 依赖(可选)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

(2) 使用 Gson

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

配置 HttpMessageConverter

@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> 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<Json> {
        @Override
        public JsonElement serialize(Json json, Type type, JsonSerializationContext jsonSerializationContext) {
            return JsonParser.parseString(json.value());
        }
    }
}

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

posted @ 2021-05-10 18:07  LB477  阅读(1079)  评论(0编辑  收藏  举报