Skip to content

[Go] optional boolean properties set to false are omitted when encodedย #7391

Open
swagger-api/swagger-codegen-generators
#1275
@drennalls

Description

@drennalls
Description

If an object defines an optional boolean property it does not end up in the JSON if the value is false

Swagger-codegen version

2.2.2

Swagger declaration file content or url
swagger: '2.0'
info:
  description: 'Demonstrate golang codegen bug'
  version: 1.0.0
schemes:
  - http
paths:
  /pet:
    post:
      summary: Add a new pet to the store
      description: ''
      operationId: addPet
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          description: Pet object that needs to be added to the store
          required: true
          schema:
            $ref: '#/definitions/Pet'
      responses:
        '405':
          description: Invalid input
definitions:
  Pet:
    title: a Pet
    description: A pet for sale in the pet store
    type: object
    required:
      - name
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
        example: doggie
      vaccinated:
        type: boolean
        description: Indicates whether the Pet's vaccinations are up-to-date
Command line used for generation

java -jar target/swagger-codegen-cli.jar generate -i ./mypetstore.yaml -l go -o ./mypetstore-client-go

Steps to reproduce

Include an optional boolean property (like vaccinated in the API above), set to false and encode it. The field will be missing from the JSON.

Related issues/PRs

If the property is marked as required then things work as expected which I guess was a result of #4665

Suggest a fix/enhancement

Don't use omitempty for boolean properties, even if optional...
from https://golang.org/pkg/encoding/json/

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

..if you do then sending a false for optional properties is not possible.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions