All Downloads are FREE. Search and download functionalities are using the official Maven repository.

go.model_anyof.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
// {{classname}} {{{description}}}{{^description}}struct for {{{classname}}}{{/description}}
type {{classname}} struct {
	{{#anyOf}}
	{{{.}}} *{{{.}}}
	{{/anyOf}}
}

// Unmarshal JSON data into any of the pointers in the struct
func (dst *{{classname}}) UnmarshalJSON(data []byte) error {
	var err error
	{{#isNullable}}
	// this object is nullable so check if the payload is null or empty string
	if string(data) == "" || string(data) == "{}" {
		return nil
	}

	{{/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 discriminator 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.{{{.}}});
	if err == nil {
		json{{{.}}}, _ := json.Marshal(dst.{{{.}}})
		if string(json{{{.}}}) == "{}" { // empty struct
			dst.{{{.}}} = nil
		} else {
			return nil // data stored in dst.{{{.}}}, return on the first match
		}
	} else {
		dst.{{{.}}} = nil
	}

	{{/anyOf}}
	return fmt.Errorf("data failed to match schemas in anyOf({{classname}})")
}

// Marshal data from the first non-nil pointers in the struct to JSON
func (src *{{classname}}) MarshalJSON() ([]byte, error) {
{{#anyOf}}
	if src.{{{.}}} != nil {
		return json.Marshal(&src.{{{.}}})
	}

{{/anyOf}}
	return nil, nil // no data in anyOf schemas
}

{{>nullable_model}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy