feat(schema): unmarshal JSON back into Schema - #1108
Open
ChrisJr404 wants to merge 1 commit into
Open
Conversation
Schema has a custom MarshalJSON that writes `type` as a `[type, "null"]` array when nullable and inlines extensions, but no matching UnmarshalJSON, so a schema it produced could not be read back: the nullable type array failed to unmarshal, and `$ref` plus `x-` extensions were silently dropped. Add UnmarshalJSON as the inverse so schemas round-trip through encoding/json.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Working towards #1016 (parsing a huma-generated document back into huma structs), I hit this:
Schemahas a customMarshalJSONbut noUnmarshalJSON, so a schema it emits cannot be read back withencoding/json.Two things break the round-trip:
typeis written as["string", "null"]when the schema is nullable, which fails to unmarshal into thestringTypefield ("cannot unmarshal array into Go struct field Schema.Type of type string").$refand anyx-extensions are silently dropped, sinceRefhas no matching JSON tag and extensions are only handled by the custom marshaler.This adds
UnmarshalJSONas the inverse ofMarshalJSON: it acceptstypeas either a plain string or the[type, "null"]array (settingNullable), reads$refintoRef, and collects unknown keys intoExtensionsthe same way they are written back out. Marshaling is unchanged.Added round-trip tests covering the nullable type array, refs, extensions, nested objects, and the invalid-type error path.