Search code examples
javaswaggeropenapiopenapi-generator

JsonIgnore using Open API spec


I use OpenAPI spec to generate Java POJOs. What do I need to specify in Open API yaml to generate the equivalent of below POJO ?

...
@JsonIgnore
public String ignoredProperty;
...

I have the yaml spec as below

openapi: 3.0.0
info:
  title: Cool API
  description: A Cool API spec
  version: 0.0.1
servers:
  - url: http://api.cool.com/v1
    description: Cool server for testing
paths:
  /
  ...
components:
  schemas:
    MyPojo:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        # I want the below attribute to be ignored as a part of JSON 
        ignoreProperty:  
          type: string  

Solution

  • the openapi generator supports vendor extensions. Specifically, for the Java generator, it supports the following extensions as of the time of writing. However, an up-to-date list can be found here.

    Extension name Description Applicable for Default value
    x-discriminator-value Used with model inheritance to specify value for discriminator that identifies current model MODEL
    x-implements Ability to specify interfaces that model must implements MODEL empty array
    x-setter-extra-annotation Custom annotation that can be specified over java setter for specific field FIELD When field is array & uniqueItems, then this extension is used to add @JsonDeserialize(as = LinkedHashSet.class) over setter, otherwise no value
    x-tags Specify multiple swagger tags for operation OPERATION null
    x-accepts Specify custom value for 'Accept' header for operation OPERATION null
    x-content-type Specify custom value for 'Content-Type' header for operation OPERATION null
    x-class-extra-annotation List of custom annotations to be added to model MODEL null
    x-field-extra-annotation List of custom annotations to be added to property FIELD null
    x-webclient-blocking Specifies if method for specific operation should be blocking or non-blocking(ex: return Mono<T>/Flux<T> or return T/List<T>/Set<T> & execute .block() inside generated method) OPERATION false

    You can use the x-field-extra-annotation vendor extension listed above to add annotations to any field. So, for your example, you can add the following:

    openapi: 3.0.0
    info:
      title: Cool API
      description: A Cool API spec
      version: 0.0.1
    servers:
      - url: http://api.cool.com/v1
        description: Cool server for testing
    paths:
      /
      ...
    components:
      schemas:
        MyPojo:
          type: object
          properties:
            id:
              type: integer
            name:
              type: string
            # I want the below attribute to be ignored as a part of JSON 
            ignoreProperty:  
              type: string  
              x-field-extra-annotation: "@com.fasterxml.jackson.annotation.JsonIgnore"