Search code examples
spring-bootjacksonswaggercode-generation

Swagger codegen ignore null fields for POJO classes


I'm making a REST API and I would like to add at the class generation the Jackson annotation to ignore null fields, so I would like to add this annotation onfly for certain classes, not for the hole project.

I know that this could be acomplished by adding in application.properties the following line :

spring.jackson.default-property-inclusion=non_null

But this is for entire project.

I see that there are some ".mustache" files

- api.mustache
- apiController.mustache

I supose that I have to add some code in one of this one, or should I insert some code in application.yml ?

I'm also using Spring Boot with Swagger-codgen.

Thank you in advance and have a nice day!


Solution

  • Ok, after few hours of research I found that because I'm using Swagger-codegen I have to search in https://github.com/swagger-api/swagger-codegen for all answers regarding Swagger-Codegen. Here are all the templates and I found that I need to add to my project the following two files

    • pojo.mustache
    • xmlAnnotation.mustache

    The path where you can find the above files is

    swagger-codegen/modules/swagger-codegen/src/main/resources/JavaSpring/
    

    More than that, those files are simple templates to generate your Pojo classes, so you need to add the @JsonInclude(JsonInclude.Include.NON_NULL) annotation in the pojo.mustache file, above the line with public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}... in order to be inserted when you generate pojo classes.

    And done, build your project again! :)