如何自定义 swagger codegen 以生成忽略 null 值的模型



我正在使用 swagger-codgen 为我的 Spring boot 应用程序生成 java 模型类,并将它们序列化为 json。默认情况下,这些模型都将包含具有 null 值的可选属性。

我想为 spring 配置 swagger-codgen 以在所有类之上包含此注释:@JsonInclude(Include.NON_NULL),以便序列化的 json 中不包含空值属性。

我怎样才能做到这一点?是否有配置选项,或者我必须手动扩展 spring 代码生成?

您可以在

application.yaml中配置它:

spring:
   jackson:
      default-property-inclusion: NON_NULL

实现这一点的一种方法是通过添加注释来修改Java Spring的pojo模板。此模板用于生成模型。

如果你没有application.yaml或application.properties,但有spring xml配置,那么添加这个也可以解决问题。
这不会将注释放在文件中,但它具有相同的效果。

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

请注意,这应该添加到使用生成的代码的应用程序中,而该应用程序不一定是生成代码的应用程序。

选项 NotNullJacksonAnnotation 是在 Swagger Codegen 2.4.15 中引入的。您可以在此处找到详细信息。请随意使用它来用@JsonInclude(Include.NON_NULL)注释您的 POJO

<build>
    <plugins>
        <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.4.15</version>
            <executions>
                <execution>
                    <id>generate-api</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>${project.basedir}/src/main/resources/swagger-api.yaml</inputSpec>
                        <language>java</language>
                        <modelPackage>org.test.model</modelPackage>
                        <configOptions>
                            <dateLibrary>java8</dateLibrary>
                            <notNullJacksonAnnotation>true</notNullJacksonAnnotation>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

最新更新