Skip to content

Inline oneOf JSON request body loses custom marshal/unmarshal behavior #2498

Closed

Description

@pomeh

Inline oneOf JSON request body loses custom marshal/unmarshal behavior

Description

When an inline oneOf schema is used as an application/json request body, the generated operation body type gets the expected union accessors and custom JSON methods. However, the generated ...JSONRequestBody is a distinct defined type and does not get equivalent methods.

Consequently, encoding/json cannot access the unexported union json.RawMessage field through the request-body type. Unmarshalling silently discards the oneOf payload, while marshalling silently omits it.

This reproduces with oapi-codegen v2.8.0 using the default templates.

Relevant generated code

type PostDemoJSONBody struct {
	Type  PostDemoJSONBodyType `json:"type"`
	union json.RawMessage
}

// PostDemoJSONRequestBody defines body for PostDemo for application/json ContentType.
type PostDemoJSONRequestBody PostDemoJSONBody

func (t PostDemoJSONBody) AsFooRequest() (FooRequest, error) { /* ... */ }
func (t *PostDemoJSONBody) FromFooRequest(v FooRequest) error { /* ... */ }
func (t PostDemoJSONBody) MarshalJSON() ([]byte, error) { /* ... */ }
func (t *PostDemoJSONBody) UnmarshalJSON(b []byte) error { /* ... */ }

PostDemoJSONRequestBody is a new defined type, not an alias. It therefore does not inherit the method set of PostDemoJSONBody.

The generated methods correctly populate and serialize PostDemoJSONBody.union, but they are bypassed when the value passed to encoding/json has type PostDemoJSONRequestBody.

Actual behavior

Given this JSON request:

{"type":"foo","another":"value"}
  • json.Unmarshal into PostDemoJSONRequestBody returns no error, but the union payload is empty. A subsequent AsFooRequest() returns unexpected end of JSON input.
  • Marshalling a populated union after converting it to PostDemoJSONRequestBody returns only {"type":"foo"}. The another property is silently lost.

Expected behavior

PostDemoJSONRequestBody should preserve the complete FooRequest payload during both marshalling and unmarshalling.

The test included below should pass and, with go test -v, print explicit confirmation:

OK: unmarshalling preserved the complete oneOf payload
OK: marshalling preserved the complete oneOf payload

Reproduction

Save the files from the appendix in the same directory, then run:

go run github.com/oapi-codegen/oapi-codegen/v2/cmd/[email protected] \
  --config config.yaml openapi.yaml
go mod tidy
go test -v ./...

Version and environment

oapi-codegen v2.8.0
github.com/oapi-codegen/runtime v1.6.0
go version go1.26.5 darwin/arm64
OpenAPI 3.0.1

Possible fix

One option is to generate an alias where preserving a distinct request-body type is unnecessary:

type PostDemoJSONRequestBody = PostDemoJSONBody

Another option is to retain the distinct type and generate delegating methods:

func (t PostDemoJSONRequestBody) MarshalJSON() ([]byte, error) {
	return PostDemoJSONBody(t).MarshalJSON()
}

func (t *PostDemoJSONRequestBody) UnmarshalJSON(data []byte) error {
	var body PostDemoJSONBody
	if err := body.UnmarshalJSON(data); err != nil {
		return err
	}
	*t = PostDemoJSONRequestBody(body)
	return nil
}

The delegation approach may be consistent with the fix for the corresponding strict-response problem, where generated wrapper types need to retain their distinct identity.

Related issues and pull requests

This appears to be the request-body wrapper counterpart of #970/#2332. PR #2348 correctly generates the union methods for PostDemoJSONBody, but those methods are still unavailable on the generated PostDemoJSONRequestBody defined type.

Workaround

Override request-bodies.tmpl so that the generated request body is an alias, or add forwarding MarshalJSON/UnmarshalJSON methods in another file in the generated package.

Complete reproducer

1. OpenAPI contract: openapi.yaml
openapi: 3.0.1

info:
  title: Demo
  version: 0.0.1

paths:
  /demo:
    post:
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - type
              properties:
                type:
                  type: string
                  enum: [foo]
              discriminator:
                propertyName: type
                mapping:
                  foo: "#/components/schemas/FooRequest"
              oneOf:
                - $ref: "#/components/schemas/FooRequest"
      responses:
        "202":
          description: irrelevant
          content:
            application/json:
              schema:
                type: object
                required:
                  - lorem
                additionalProperties: false
                properties:
                  lorem:
                    type: string

components:
  schemas:
    FooRequest:
      type: object
      required:
        - type
        - another
      additionalProperties: false
      properties:
        type:
          type: string
          enum: [foo]
          nullable: false
        another:
          type: string
          nullable: false
2. Generator configuration: config.yaml
# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/v2.8.0/configuration-schema.json
package: demo
output: client.go
generate:
  models: true

output-options:
  skip-enum-validate: true
  response-type-suffix: Resp
  skip-client-response-content-type: true
  prefer-skip-optional-pointer: true
3. Generated code: client.go
// Package demo provides primitives to interact with the openapi HTTP API.
//
// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.8.0 DO NOT EDIT.
package demo

import (
	"encoding/json"
	"errors"
	"fmt"

	"github.com/oapi-codegen/runtime"
)

// Defines values for FooRequestType.
const (
	FooRequestTypeFoo FooRequestType = "foo"
)

// Defines values for PostDemoJSONBodyType.
const (
	PostDemoJSONBodyTypeFoo PostDemoJSONBodyType = "foo"
)

// FooRequest defines model for FooRequest.
type FooRequest struct {
	Another string         `json:"another"`
	Type    FooRequestType `json:"type"`
}

// FooRequestType defines model for FooRequest.Type.
type FooRequestType string

// PostDemoJSONBody defines parameters for PostDemo.
type PostDemoJSONBody struct {
	Type  PostDemoJSONBodyType `json:"type"`
	union json.RawMessage
}

// PostDemoJSONBodyType defines parameters for PostDemo.
type PostDemoJSONBodyType string

// PostDemoJSONRequestBody defines body for PostDemo for application/json ContentType.
type PostDemoJSONRequestBody PostDemoJSONBody

// AsFooRequest returns the union data inside the PostDemoJSONBody as a FooRequest
func (t PostDemoJSONBody) AsFooRequest() (FooRequest, error) {
	var body FooRequest
	err := json.Unmarshal(t.union, &body)
	return body, err
}

// FromFooRequest overwrites any union data inside the PostDemoJSONBody as the provided FooRequest
func (t *PostDemoJSONBody) FromFooRequest(v FooRequest) error {
	t.Type = "foo"
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}
	b, err = runtime.JSONMerge(b, []byte(`{"type":"foo"}`))
	t.union = b
	return err
}

// MergeFooRequest performs a merge with any union data inside the PostDemoJSONBody, using the provided FooRequest
func (t *PostDemoJSONBody) MergeFooRequest(v FooRequest) error {
	t.Type = "foo"
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}
	b, err = runtime.JSONMerge(b, []byte(`{"type":"foo"}`))
	if err != nil {
		return err
	}

	merged, err := runtime.JSONMerge(t.union, b)
	t.union = merged
	return err
}

func (t PostDemoJSONBody) Discriminator() (string, error) {
	var discriminator struct {
		Discriminator string `json:"type"`
	}
	err := json.Unmarshal(t.union, &discriminator)
	return discriminator.Discriminator, err
}

func (t PostDemoJSONBody) ValueByDiscriminator() (interface{}, error) {
	discriminator, err := t.Discriminator()
	if err != nil {
		return nil, err
	}
	switch discriminator {
	case "foo":
		return t.AsFooRequest()
	default:
		return nil, errors.New("unknown discriminator value: " + discriminator)
	}
}

func (t PostDemoJSONBody) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	if err != nil {
		return nil, err
	}
	object := make(map[string]json.RawMessage)
	if t.union != nil {
		err = json.Unmarshal(b, &object)
		if err != nil {
			return nil, err
		}
	}

	object["type"], err = json.Marshal(t.Type)
	if err != nil {
		return nil, fmt.Errorf("error marshaling 'type': %w", err)
	}

	b, err = json.Marshal(object)
	return b, err
}

func (t *PostDemoJSONBody) UnmarshalJSON(b []byte) error {
	err := t.union.UnmarshalJSON(b)
	if err != nil {
		return err
	}
	object := make(map[string]json.RawMessage)
	err = json.Unmarshal(b, &object)
	if err != nil {
		return err
	}

	if raw, found := object["type"]; found {
		err = json.Unmarshal(raw, &t.Type)
		if err != nil {
			return fmt.Errorf("error reading 'type': %w", err)
		}
	}

	return err
}
4. Reproduction tests: client_test.go
package demo

import (
	"encoding/json"
	"testing"
)

func TestPostDemoJSONRequestBodyUnmarshal(t *testing.T) {
	const input = `{"type":"foo","another":"value"}`

	var request PostDemoJSONRequestBody
	if err := json.Unmarshal([]byte(input), &request); err != nil {
		t.Fatalf("unmarshal request body: %v", err)
	}

	decoded, err := PostDemoJSONBody(request).AsFooRequest()
	if err != nil {
		t.Fatalf("decode FooRequest variant: %v", err)
	}
	if decoded.Another != "value" {
		t.Fatalf("oneOf payload was lost: got %+v", decoded)
	}
	t.Logf("OK: unmarshalling preserved the complete oneOf payload: %+v", decoded)
}

func TestPostDemoJSONRequestBodyMarshal(t *testing.T) {
	var body PostDemoJSONBody
	if err := body.FromFooRequest(FooRequest{
		Type:    FooRequestTypeFoo,
		Another: "value",
	}); err != nil {
		t.Fatalf("populate union body: %v", err)
	}

	encoded, err := json.Marshal(PostDemoJSONRequestBody(body))
	if err != nil {
		t.Fatalf("marshal request body: %v", err)
	}

	var got map[string]any
	if err := json.Unmarshal(encoded, &got); err != nil {
		t.Fatalf("decode generated JSON: %v", err)
	}
	if got["another"] != "value" {
		t.Fatalf("oneOf payload was lost: got %s", encoded)
	}
	t.Logf("OK: marshalling preserved the complete oneOf payload: %s", encoded)
}
5. Current test output with v2.8.0
$ go test -v ./...
=== RUN   TestPostDemoJSONRequestBodyUnmarshal
    client_test.go:18: decode FooRequest variant: unexpected end of JSON input
--- FAIL: TestPostDemoJSONRequestBodyUnmarshal (0.00s)
=== RUN   TestPostDemoJSONRequestBodyMarshal
    client_test.go:45: oneOf payload was lost: got {"type":"foo"}
--- FAIL: TestPostDemoJSONRequestBodyMarshal (0.00s)
FAIL
FAIL    example.com/oapi-codegen-repro    0.464s
FAIL

After a fix, the same command should instead produce output similar to:

=== RUN   TestPostDemoJSONRequestBodyUnmarshal
    client_test.go:23: OK: unmarshalling preserved the complete oneOf payload: {Another:value Type:foo}
--- PASS: TestPostDemoJSONRequestBodyUnmarshal (0.00s)
=== RUN   TestPostDemoJSONRequestBodyMarshal
    client_test.go:47: OK: marshalling preserved the complete oneOf payload: {"another":"value","type":"foo"}
--- PASS: TestPostDemoJSONRequestBodyMarshal (0.00s)
PASS

Activity

  1. added a commit that references this issue on Jul 31, 2026
    b024e15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions