Skip to content

x-omitempty

Force the presence of the JSON tag omitempty on a field.

Overview

In a case that you may want to add the JSON struct tag omitempty to types that don't have one generated by default - for instance a required field - you can use the x-omitempty extension.

Example

openapi: "3.0.0"
info:
  version: 1.0.0
  title: x-omitempty
components:
  schemas:
    Client:
      type: object
      required:
        - name
      properties:
        name:
          type: string
        id:
          type: number
    ClientWithExtension:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          # for some reason, you may want this behaviour, even though it's a required field
          x-omitempty: true
        id:
          type: number

Generated Code

From here, we now get two different models:

type Client struct {
    Name string   `json:"name" validate:"required"`
    ID   *float32 `json:"id,omitempty"`
}
type ClientWithExtension struct {
    Name string   `json:"name,omitempty" validate:"required"`
    ID   *float32 `json:"id,omitempty"`
}

Full Example

You can see this in more detail in the example code.