Skip to content

Commit 4e73d8a

Browse files
committed
Only unmarshal oneOf structs once.
1 parent 5ed6c43 commit 4e73d8a

File tree

2 files changed

+123
-181
lines changed

2 files changed

+123
-181
lines changed

internal/generate/types.go

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,7 @@ func writeTypes(f *os.File, typeCollection []TypeTemplate, typeValidationCollect
368368
// Check the discriminator to decide which type to unmarshal to.
369369
fmt.Fprintf(f, "\tvar peek struct {\n")
370370
fmt.Fprintf(f, "\t\tDiscriminator %s `json:\"%s\"`\n", tt.DiscriminatorType, tt.DiscriminatorKey)
371+
fmt.Fprintf(f, "\t\tValue json.RawMessage `json:\"%s\"`\n", strings.ToLower(tt.VariantField))
371372
fmt.Fprintf(f, "\t}\n")
372373
fmt.Fprintf(f, "\tif err := json.Unmarshal(data, &peek); err != nil {\n")
373374
fmt.Fprintf(f, "\t\treturn err\n")
@@ -380,17 +381,14 @@ func writeTypes(f *os.File, typeCollection []TypeTemplate, typeValidationCollect
380381

381382
// For objects, unmarshal into the corresponding struct. For simple types, unmarshal into a temporary struct, then grab the value from it.
382383
if isSimpleType(mapping.ObjectType) {
383-
fmt.Fprintf(f, "\t\ttype value struct {\n")
384-
fmt.Fprintf(f, "\t\t\tValue %s `json:\"%s\"`\n", mapping.ConcreteType, strings.ToLower(tt.VariantField))
385-
fmt.Fprintf(f, "\t\t}\n")
386-
fmt.Fprintf(f, "\t\tvar val value\n")
387-
fmt.Fprintf(f, "\t\tif err := json.Unmarshal(data, &val); err != nil {\n")
384+
fmt.Fprintf(f, "\t\tvar val %s\n", mapping.ConcreteType)
385+
fmt.Fprintf(f, "\t\tif err := json.Unmarshal(peek.Value, &val); err != nil {\n")
388386
fmt.Fprintf(f, "\t\t\treturn err\n")
389387
fmt.Fprintf(f, "\t\t}\n")
390-
fmt.Fprintf(f, "\tv.%s = val.Value\n", tt.VariantField)
388+
fmt.Fprintf(f, "\tv.%s = val\n", tt.VariantField)
391389
} else {
392390
fmt.Fprintf(f, "\t\tvar val %s\n", mapping.ConcreteType)
393-
fmt.Fprintf(f, "\t\tif err := json.Unmarshal(data, &val); err != nil {\n")
391+
fmt.Fprintf(f, "\t\tif err := json.Unmarshal(peek.Value, &val); err != nil {\n")
394392
fmt.Fprintf(f, "\t\t\treturn err\n")
395393
fmt.Fprintf(f, "\t\t}\n")
396394
fmt.Fprintf(f, "\tv.%s = val\n", tt.VariantField)

0 commit comments

Comments
 (0)