[Go][Experimental] Add discriminator support to anyOf (#6511)

* add discriminator support in anyof

* update samples
This commit is contained in:
William Cheng
2020-06-02 10:54:57 +08:00
committed by GitHub
parent 58ed6afc0d
commit 4c3eb0d973
2 changed files with 31 additions and 1 deletions

View File

@@ -15,6 +15,35 @@ func (dst *{{classname}}) UnmarshalJSON(data []byte) error {
}
{{/isNullable}}
{{#discriminator}}
{{#mappedModels}}
{{#-first}}
// use discriminator value to speed up the lookup
var jsonDict map[string]interface{}
err := json.Unmarshal(data, &jsonDict)
if err != nil {
return fmt.Errorf("Failed to unmarshal JSON into map for the discrimintor lookup.")
}
{{/-first}}
// check if the discriminator value is '{{{mappingName}}}'
if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" {
// try to unmarshal JSON data into {{{modelName}}}
err = json.Unmarshal(data, &dst.{{{modelName}}});
if err == nil {
json{{{modelName}}}, _ := json.Marshal(dst.{{{modelName}}})
if string(json{{{modelName}}}) == "{}" { // empty struct
dst.{{{modelName}}} = nil
} else {
return nil // data stored in dst.{{{modelName}}}, return on the first match
}
} else {
dst.{{{modelName}}} = nil
}
}
{{/mappedModels}}
{{/discriminator}}
{{#anyOf}}
// try to unmarshal JSON data into {{{.}}}
err = json.Unmarshal(data, &dst.{{{.}}});
@@ -44,4 +73,4 @@ func (src *{{classname}}) MarshalJSON() ([]byte, error) {
return nil, nil // no data in anyOf schemas
}
{{>nullable_model}}
{{>nullable_model}}

View File

@@ -101,3 +101,4 @@ func (v *NullableGmFruit) UnmarshalJSON(src []byte) error {
return json.Unmarshal(src, &v.value)
}