x-go-json-ignore¶
When (un)marshaling JSON, ignore field(s).
Overview¶
By default, oapi-codegen will generate json:"..." struct tags for all fields in a struct, so JSON (un)marshaling works.
However, sometimes, you want to omit fields, which can be done with the x-go-json-ignore extension.
Example¶
openapi: "3.0.0"
info:
version: 1.0.0
title: x-go-json-ignore
components:
schemas:
Client:
type: object
required:
- name
properties:
name:
type: string
complexField:
type: object
properties:
name:
type: string
accountName:
type: string
# ...
ClientWithExtension:
type: object
required:
- name
properties:
name:
type: string
complexField:
type: object
properties:
name:
type: string
accountName:
type: string
# ...
x-go-json-ignore: true
Generated Code¶
From here, we now get two different models:
type Client struct {
Name string `json:"name" validate:"required"`
ComplexField *Client_ComplexField `json:"complexField,omitempty"`
}
type Client_ComplexField struct {
Name *string `json:"name,omitempty"`
AccountName *string `json:"accountName,omitempty"`
}
type ClientWithExtension struct {
Name string `json:"name" validate:"required"`
ComplexField *ClientWithExtension_ComplexField `json:"-"`
}
type ClientWithExtension_ComplexField struct {
Name *string `json:"name,omitempty"`
AccountName *string `json:"accountName,omitempty"`
}
Notice that the ComplexField is still generated in full, but the type will then be ignored with JSON marshalling (json:"-").
Full Example¶
You can see this in more detail in the example code.
Related Extensions¶
x-omitempty- Force the presence of the JSON tagomitemptyon a fieldx-oapi-codegen-extra-tags- Generate arbitrary struct tags