如果我在 application.properties 中使用 json 到 gson 映射器 属性,为什么 swagger 不起作用

why swagger is not working if i use the json to gson mapper property in application.properties

我们在 Spring boot application.properties 中使用 spring.http.converters.preferred-json-mapper=gson 属性 从 json 转换为 gson对于 Junit 测试用例。不确定是什么导致了这个 属性 大摇大摆。

与 swagger 集成时出现获取错误。

我知道这是一个 "old" post 你可能还有答案。 spring-boot 做的是音符魔术。根据您的应用程序配置(依赖项 class、文件等),它将尝试自动配置您的应用程序。

所以默认情况下你有这个spring配置

# HTTP (HttpProperties)
spring.http.converters.preferred-json-mapper= # Preferred JSON mapper to use for HTTP message conversion. By default, auto-detected according to the environment.

要启用 gson,您必须包含 GSON 依赖项:

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

这将允许 spring-boot 检测 Gson 对您的 class 路径的依赖。

将 json 映射器设置为 gson:

# Preferred JSON mapper to use for HTTP message conversion.
spring.http.converters.preferred-json-mapper=gson

在 spring 启动时配置 Gson

# GSON ([GsonProperties][1])
spring.gson.date-format= # Format to use when serializing Date objects.
spring.gson.disable-html-escaping= # Whether to disable the escaping of HTML characters such as '<', '>', etc.
spring.gson.disable-inner-class-serialization= # Whether to exclude inner classes during serialization.
spring.gson.enable-complex-map-key-serialization= # Whether to enable serialization of complex map keys (i.e. non-primitives).
spring.gson.exclude-fields-without-expose-annotation= # Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation.
spring.gson.field-naming-policy= # Naming policy that should be applied to an object's field during serialization and deserialization.
spring.gson.generate-non-executable-json= # Whether to generate non executable JSON by prefixing the output with some special text.
spring.gson.lenient= # Whether to be lenient about parsing JSON that doesn't conform to RFC 4627.
spring.gson.long-serialization-policy= # Serialization policy for Long and long types.
spring.gson.pretty-printing= # Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.serialize-nulls= # Whether to serialize null fields.

你也可以在你的项目中完全排除 jackson 做:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- Exclude the default Jackson dependency -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>