github.com/oam-dev/kubevela@v1.9.11/pkg/definition/gen_sdk/openapi-generator/templates/go/model_anyof.mustache (about) 1 // {{classname}} {{{description}}}{{^description}}struct for {{{classname}}}{{/description}} 2 type {{classname}} struct { 3 {{#anyOf}} 4 {{{.}}} *{{{.}}} 5 {{/anyOf}} 6 } 7 8 // Unmarshal JSON data into any of the pointers in the struct 9 func (dst *{{classname}}) UnmarshalJSON(data []byte) error { 10 var err error 11 {{#isNullable}} 12 // this object is nullable so check if the payload is null or empty string 13 if string(data) == "" || string(data) == "{}" { 14 return nil 15 } 16 17 {{/isNullable}} 18 {{#discriminator}} 19 {{#mappedModels}} 20 {{#-first}} 21 // use discriminator value to speed up the lookup 22 var jsonDict map[string]interface{} 23 err = json.Unmarshal(data, &jsonDict) 24 if err != nil { 25 return fmt.Errorf("failed to unmarshal JSON into map for the discriminator lookup") 26 } 27 28 {{/-first}} 29 // check if the discriminator value is '{{{mappingName}}}' 30 if jsonDict["{{{propertyBaseName}}}"] == "{{{mappingName}}}" { 31 // try to unmarshal JSON data into {{{modelName}}} 32 err = json.Unmarshal(data, &dst.{{{modelName}}}); 33 if err == nil { 34 json{{{modelName}}}, _ := json.Marshal(dst.{{{modelName}}}) 35 if string(json{{{modelName}}}) == "{}" { // empty struct 36 dst.{{{modelName}}} = nil 37 } else { 38 return nil // data stored in dst.{{{modelName}}}, return on the first match 39 } 40 } else { 41 dst.{{{modelName}}} = nil 42 } 43 } 44 45 {{/mappedModels}} 46 {{/discriminator}} 47 {{#anyOf}} 48 // try to unmarshal JSON data into {{{.}}} 49 err = json.Unmarshal(data, &dst.{{{.}}}); 50 if err == nil { 51 json{{{.}}}, _ := json.Marshal(dst.{{{.}}}) 52 if string(json{{{.}}}) == "{}" { // empty struct 53 dst.{{{.}}} = nil 54 } else { 55 return nil // data stored in dst.{{{.}}}, return on the first match 56 } 57 } else { 58 dst.{{{.}}} = nil 59 } 60 61 {{/anyOf}} 62 return fmt.Errorf("data failed to match schemas in anyOf({{classname}})") 63 } 64 65 // Marshal data from the first non-nil pointers in the struct to JSON 66 func (src *{{classname}}) MarshalJSON() ([]byte, error) { 67 {{#anyOf}} 68 if src.{{{.}}} != nil { 69 return json.Marshal(&src.{{{.}}}) 70 } 71 72 {{/anyOf}} 73 return nil, nil // no data in anyOf schemas 74 } 75 76 {{>nullable_model}}