Skip to content

Commit 915af3a

Browse files
authored
if discriminator is not defined with useOneOfDiscriminatorLookup set to true, we generated as useOneOfDiscriminatorLookup false (#11178)
1 parent c8fff9a commit 915af3a

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

modules/openapi-generator/src/main/resources/go/model_oneof.mustache

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,38 @@ func (dst *{{classname}}) UnmarshalJSON(data []byte) error {
4848
}
4949

5050
{{/mappedModels}}
51-
{{/discriminator}}
5251
return nil
52+
{{/discriminator}}
53+
{{^discriminator}}
54+
match := 0
55+
{{#oneOf}}
56+
// try to unmarshal data into {{{.}}}
57+
err = json.Unmarshal(data, &dst.{{{.}}})
58+
if err == nil {
59+
json{{{.}}}, _ := json.Marshal(dst.{{{.}}})
60+
if string(json{{{.}}}) == "{}" { // empty struct
61+
dst.{{{.}}} = nil
62+
} else {
63+
match++
64+
}
65+
} else {
66+
dst.{{{.}}} = nil
67+
}
68+
69+
{{/oneOf}}
70+
if match > 1 { // more than 1 match
71+
// reset to nil
72+
{{#oneOf}}
73+
dst.{{{.}}} = nil
74+
{{/oneOf}}
75+
76+
return fmt.Errorf("Data matches more than one schema in oneOf({{classname}})")
77+
} else if match == 1 {
78+
return nil // exactly one match
79+
} else { // no match
80+
return fmt.Errorf("Data failed to match schemas in oneOf({{classname}})")
81+
}
82+
{{/discriminator}}
5383
{{/useOneOfDiscriminatorLookup}}
5484
{{^useOneOfDiscriminatorLookup}}
5585
match := 0

0 commit comments

Comments
 (0)