Content-Length: 256454 | pFad | http://github.com/oapi-codegen/oapi-codegen/pull/1931

EB fix(codegen): update JSON tags to include omitempty for nullable fields by Dumbris · Pull Request #1931 · oapi-codegen/oapi-codegen · GitHub
Skip to content

fix(codegen): update JSON tags to include omitempty for nullable fields #1931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Dumbris
Copy link

@Dumbris Dumbris commented Mar 17, 2025

Fix omitempty tag for nullable fields

Description

This PR fixes a bug in the JSON tag generation for struct fields that represent nullable but non-required properties in OpenAPI schemas.

The issue was in the conditional logic that determines when to add the omitempty tag:

// Before
shouldOmitEmpty := (!p.Required || p.ReadOnly || p.WriteOnly) &&
    (!p.Required || !p.ReadOnly || !globalState.options.Compatibility.DisableRequiredReadOnlyAsPointer)

omitEmpty := !p.Nullable && shouldOmitEmpty

The bug occurred because !p.Nullable would be false for nullable fields, causing omitEmpty to be false even when the field wasn't required. This led to nullable but optional fields incorrectly missing the omitempty tag.

Changes

  • Fixed the conditional logic to correctly apply omitempty to all non-required fields regardless of nullability
  • Updated tests to verify the corrected behavior

Why this makes sense

  1. According to the OpenAPI spec, nullable: true means a value can be null, while the required array determines if a property must be present
  2. In Go, the omitempty tag controls whether a field is omitted when it's the zero value (not directly related to nullability)
  3. Non-required fields should have omitempty to correctly handle JSON serialization when the field is absent

This change ensures the generated code better aligns with both OpenAPI semantics and Go's JSON marshaling conventions.

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

Successfully merging this pull request may close these issues.

2 participants








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/oapi-codegen/oapi-codegen/pull/1931

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy