From d4912b424d8ec46953e479379dd8c435dc3118ef Mon Sep 17 00:00:00 2001 From: K Zhang Date: Mon, 17 Jan 2022 11:08:15 -0500 Subject: [PATCH] if discriminator is not defined with useOneOfDiscriminatorLookup set to true, we generated as useOneOfDiscriminatorLookup false (#11178) --- .../main/resources/go/model_oneof.mustache | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/go/model_oneof.mustache b/modules/openapi-generator/src/main/resources/go/model_oneof.mustache index 45562dcc7c30..6938308d763e 100644 --- a/modules/openapi-generator/src/main/resources/go/model_oneof.mustache +++ b/modules/openapi-generator/src/main/resources/go/model_oneof.mustache @@ -48,8 +48,38 @@ func (dst *{{classname}}) UnmarshalJSON(data []byte) error { } {{/mappedModels}} - {{/discriminator}} return nil + {{/discriminator}} + {{^discriminator}} + match := 0 + {{#oneOf}} + // try to unmarshal data into {{{.}}} + err = json.Unmarshal(data, &dst.{{{.}}}) + if err == nil { + json{{{.}}}, _ := json.Marshal(dst.{{{.}}}) + if string(json{{{.}}}) == "{}" { // empty struct + dst.{{{.}}} = nil + } else { + match++ + } + } else { + dst.{{{.}}} = nil + } + + {{/oneOf}} + if match > 1 { // more than 1 match + // reset to nil + {{#oneOf}} + dst.{{{.}}} = nil + {{/oneOf}} + + return fmt.Errorf("Data matches more than one schema in oneOf({{classname}})") + } else if match == 1 { + return nil // exactly one match + } else { // no match + return fmt.Errorf("Data failed to match schemas in oneOf({{classname}})") + } + {{/discriminator}} {{/useOneOfDiscriminatorLookup}} {{^useOneOfDiscriminatorLookup}} match := 0