I am working with a JSON response that can sometimes return a string or an object with string keys but values that are string and bool. I understand I need to implement my own Unmarshaler for the data
Example JSON Situations:
caseOne := `"data": [
{"user": "usersName"}
]`
caseTwo := `"data": [
{"user": {"id": "usersId", "isActive": true}}
]`
My Code:
package main
type Result struct {
Data []Item `json:"data"`
}
type Item struct {
User User `json:"user"`
}
type User struct {
user string
}
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(u.user)
}
func (u *User) UnmarshalJSON(data []byte) error {
var raw interface{}
json.Unmarshal(data, &raw)
switch raw := raw.(type) {
case string:
*u = User{raw}
case map[string]interface{}:
// how do I handle the other "isActive" key that is map[string]bool?
*u = User{raw["id"].(string)}
}
return nil
}
This question/answer: Here comes close to answering my use case but I am a bit stuck on how to handle multiple map values of different value types.
Current Go Playground: Here