Reputation: 1440
I'm using swagger-codgen to generate java model classes for my spring boot application and serialize them as json. By default these models would all include optional properties with null values.
I would like to configure the swagger-codgen for spring to include this annotation on top of all classes: @JsonInclude(Include.NON_NULL)
so that null valued properties are not included in the serialized json.
How can i achieve this? Is there a configuration option or do i have to extend the spring codegen manually?
Upvotes: 4
Views: 15691
Reputation: 29
The option NotNullJacksonAnnotation
was introduced in Swagger Codegen 2.4.15. You can find details here. Please feel free to use it to have your POJOs annotated with @JsonInclude(Include.NON_NULL)
.
<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>
Upvotes: -1
Reputation: 2243
If you don't have application.yaml or application.properties but do have spring xml configuration, then adding this will also do the trick.
This will not put the annotation in the files but it has the same effect.
<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>
Note that this should be added in the application that uses your generated code, which is not necessarily the one that generated it.
Upvotes: 0
Reputation: 172
You can configure that in your application.yaml
:
spring:
jackson:
default-property-inclusion: NON_NULL
Upvotes: 7
Reputation: 4481
One way of achieving that would be modifying the pojo template for Java Spring by adding the annotation. This template is used to generate the models.
Upvotes: 4