Given the following JSON string:
{
"username":"bob",
"name":"Robert",
"locations": [
{
"city": "Paris",
"country": "France"
},
{
"city": "Los Angeles",
"country": "US"
}
]
}
I need a way to unmarshal this into the a struct like this:
type User struct {
Username string
Name string
Cities []string
}
Where Cities is a slice containing the "city" values, and "country" is discarded.
I think this can be done using a custom JSON.Unmarshal function, but not sure how to do that.
>Solution :
You can define new type for Cities and implement custom Unmarshaler:
type User struct {
Username string `json:"username"`
Name string `json:"name"`
Cities []Cities `json:"locations"`
}
type Cities string
func (c *Cities) UnmarshalJSON(data []byte) error {
tmp := struct {
City string `json:"city"`
}{}
err := json.Unmarshal(data, &tmp)
if err != nil {
return err
}
*c = Cities(tmp.City)
return nil
}