type State struct {
Type string `json:"type" validate:"required"`
Value string `json:"value"`
}
I have a struct like this. I need to pass the state to the API in different types.
eg: state can be either { type: 'boolean', value: true }
or { type: 'string', value: 'ABC' }
And I'm storing it ( the value ) as a string in db.
Then when I'm passing from an API, I need to set the particular value considering the type (not as a string).
Same as this { type: 'boolean', value: true }
, { type: 'string', value: 'ABC' }
How can I achieve this with Marshalling and Unmarshalling?
You can define marshal and unmarshal logic in your code.
type State struct {
Type string `json:"type" validate:"required"`
Value interface{} `json:"value"`
}
func (s *State) UnmarshalJSON(b []byte) (err error) {
tmpMap := map[string]string{}
err = json.Unmarshal(b, &tmpMap)
if err != nil {
return err
}
if tmpMap["type"] == "" {
return errors.New("type not present")
}
if tmpMap["value"] == "" {
return errors.New("value not present")
}
if tmpMap["type"] == "string" {
s.Type = "string"
s.Value = tmpMap["value"]
} else if tmpMap["type"] == "boolean" {
s.Type = "boolean"
s.Value = tmpMap["value"] == "true"
} else {
//TODO implements other type
return errors.New(fmt.Sprintf("Unknown type %s", tmpMap["type"]))
}
return nil
}
See https://play.golang.org/p/BnD7HAuURzJ
Similarly, you can define MarshalJSON
method on State
struct to handle data serialization.
func (c State) MarshalJSON() ([]byte, error)
To store State
db in single column in db you can implement
func (c State) Value() (driver.Value, error)
To build a state from DB columns you need to implement Scan
method as
func (e *State) Scan(value interface{}) error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.