Skip to content

bug: MarshalJSON (and UnmarshalJSON) are not generated for the ResponseObject when the response is a oneOf schema #1665

Closed

Description

@akishichinibu
❯ go version
go version go1.22.1 darwin/arm64
❯ oapi-codegen --version
github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
v2.3.0

Hi👋 , I think there's a bug in oapi-codegen v2.3.0 and there's a minimal example to reproduce the problem

oapi-codegen -config config.yaml test.yaml

config.yaml

# yaml-language-server: $schema=https://raw.githubusercontent.com/deepmap/oapi-codegen/HEAD/configuration-schema.json
package: "api"
generate:
  echo-server: true
  models: true
  strict-server: true
  embedded-spec: false
output: api.gen.go
output-options:
  nullable-type: true
  initialism-overrides: true

test.yaml

openapi: 3.0.3
info:
  title: Swagger Petstore - OpenAPI 3.0
  version: 1.0.11
paths:
  /pet/findByStatus:
    get:
      tags:
        - pet
      summary: Finds Pets by status
      description: Multiple status values can be provided with comma separated strings
      operationId: findPetsByStatus
      responses:
        '200':
          description: successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PP'
components:
  schemas:
    Pet1:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 10
        name:
          type: string
          example: doggie
    Pet2:
      type: object
      properties:
        id:
          type: integer
          format: int64
          example: 10
        name:
          type: string
          example: doggie
    PP:
      type: object
      oneOf:
        - "$ref": "#/components/schemas/Pet1"
        - "$ref": "#/components/schemas/Pet2"

Part of the generated server code

type PP struct {
	union json.RawMessage
}

func (t PP) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	return b, err
}

func (t *PP) UnmarshalJSON(b []byte) error {
	err := t.union.UnmarshalJSON(b)
	return err
}

type FindPetsByStatusResponseObject interface {
	VisitFindPetsByStatusResponse(w http.ResponseWriter) error
}

type FindPetsByStatus200JSONResponse PP

func (response FindPetsByStatus200JSONResponse) VisitFindPetsByStatusResponse(w http.ResponseWriter) error {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)

	return json.NewEncoder(w).Encode(response)
}

The MarshalJSON was generated correctly for PP but NOT for the response object in strict-server mode.
Because there's only one private member union in PP, when the user try to return a FindPetsByStatusResponseObject in handler like the code below

var p PP
p.FromPet1(...)
return FindPetsByStatus200JSONResponse(p), nil

the responseObject will be marshal to an empty JSON.

I think an additional MarshalJSON(and UnmarshalJSON) should be generated when the response is a oneOf schema.

func (t FindPetsByStatus200JSONResponse) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	return b, err
}

Activity

  1. akishichinibu commented on Jun 19, 2024

    @akishichinibu
    Author

    I think this issue is related to #1620

  2. akishichinibu commented on Jun 20, 2024

    @akishichinibu
    Author

    I found a temporary workaround by using a user template. In the strict-interface template, check if the response's OpenAPI schema is oneOf when the contentType is JSON.

    curl https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.3.0/pkg/codegen/templates/strict/strict-interface.tmpl -o strict-interface.tmpl
    patch strict-interface.tmpl -o strict-interface.patched.tmpl  < strict-interface.patch
    74a75,81
    >             {{if eq .NameTagOrContentType "JSON" -}}
    >             {{if or (ne 0 (len .Schema.OAPISchema.OneOf)) (ne 0 (len .Schema.OAPISchema.AnyOf)) (ne 0 (len .Schema.OAPISchema.AllOf)) -}}
    >             func (response {{$receiverTypeName}}) MarshalJSON() ([]byte, error) {
    >                 return response.union.MarshalJSON()
    >             }
    >             {{end -}}
    >             {{end -}}
    

    config.yaml

    # yaml-language-server: $schema=https://raw.githubusercontent.com/deepmap/oapi-codegen/HEAD/configuration-schema.json
    package: "api"
    generate:
      echo-server: true
      models: true
      strict-server: true
      embedded-spec: false
    output: api.gen.go
    output-options:
      nullable-type: true
      initialism-overrides: true
      user-templates:
        strict/strict-interface.tmpl: ./strict-interface.patched.tmpl
  3. dan-j commented on Jun 20, 2024

    @dan-j

    This issue is also discussed here #970. It comes with a PR #1231 but I'm not sure if it should be merged due to my final comment in the issue

  4. akishichinibu commented on Jun 24, 2024

    @akishichinibu
    Author

    Also discussed under #970 (comment)
    I seems that there're two ways to fix this bug.

  5. self-assigned this
    on Jul 3, 2024
  6. added this to the v2.4.0 milestone on Jul 3, 2024
  7. modified the milestones: v2.4.0, v2.5.0 on Sep 20, 2024
  8. stefanmcshane commented on Nov 14, 2024

    @stefanmcshane

    I found a temporary workaround by using a user template. In the strict-interface template, check if the response's OpenAPI schema is oneOf when the contentType is JSON.

    curl https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.3.0/pkg/codegen/templates/strict/strict-interface.tmpl -o strict-interface.tmpl
    patch strict-interface.tmpl -o strict-interface.patched.tmpl  < strict-interface.patch
    74a75,81
    >             {{if eq .NameTagOrContentType "JSON" -}}
    >             {{if or (ne 0 (len .Schema.OAPISchema.OneOf)) (ne 0 (len .Schema.OAPISchema.AnyOf)) (ne 0 (len .Schema.OAPISchema.AllOf)) -}}
    >             func (response {{$receiverTypeName}}) MarshalJSON() ([]byte, error) {
    >                 return response.union.MarshalJSON()
    >             }
    >             {{end -}}
    >             {{end -}}

    config.yaml

    # yaml-language-server: $schema=https://raw.githubusercontent.com/deepmap/oapi-codegen/HEAD/configuration-schema.json
    package: "api"
    generate:
      echo-server: true
      models: true
      strict-server: true
      embedded-spec: false
    output: api.gen.go
    output-options:
      nullable-type: true
      initialism-overrides: true
      user-templates:
        strict/strict-interface.tmpl: ./strict-interface.patched.tmpl

    @akishichinibu i cant get your curl to work as I dont know what your specific strict-interface.patch file is. Can you provide an outline or a link to a working patch you have so I can diff it?

  9. akishichinibu commented on Nov 14, 2024

    @akishichinibu
    Author

    @stefanmcshane
    The content of the patch file is here. Just below the curl.

    strict-interface.patch

    74a75,81
    >             {{if eq .NameTagOrContentType "JSON" -}}
    >             {{if or (ne 0 (len .Schema.OAPISchema.OneOf)) (ne 0 (len .Schema.OAPISchema.AnyOf)) (ne 0 (len .Schema.OAPISchema.AllOf)) -}}
    >             func (response {{$receiverTypeName}}) MarshalJSON() ([]byte, error) {
    >                 return response.union.MarshalJSON()
    >             }
    >             {{end -}}
    >             {{end -}}
  10. stefanmcshane commented on Nov 14, 2024

    @stefanmcshane

    Thanks - I see my mistake now. This applies the fix for responses, but not request bodies. Works a charm on 2.4.1 responses FWIW

  11. nustiueudinastea commented on Dec 4, 2024

    @nustiueudinastea

    For anyone that applies this patch to the latest 2.4.1 version, make sure to adjust the line number because things shifted a bit in the latest strict-interface.tmpl file.

  12. modified the milestones: v2.5.0, v2.6.0 on May 11, 2025
  13. mromaszewicz commented on Apr 22, 2026

    @mromaszewicz
    Member

    This is a duplicate of #970. Both describe the same bug: when a strict-server response content schema is a $ref to a oneOf/anyOf union, the generated response type (e.g. type FindPetsByStatus200JSONResponse PP) is a named defined type and does not inherit the union's MarshalJSON, so encoding produces {}.

    A fix is pending in #2332, which generates delegating MarshalJSON/UnmarshalJSON on the response type for this case (exactly what you proposed). Closing here in favor of #970; please subscribe to #2332 for merge updates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions