Suppose I define a struct as following:
type User struct {
ID string
Name string
Age uint
City string `json:"address.city"`
Province string `json:"address.province"`
}
I am able to take a User struct, and expand out the flattened fiends into a nested JSON structure, with an address object. I'm struggling however to go in the other direction.
How would I take the following JSON:
{
"ID": "1",
"Name": "Keith Baldwin",
"Age": 30,
"address": {
"city": "Saskatoon",
"province": "Saskatchewan"
}
}
And unmarshal it into the given struct?
Is there something I'm missing, or will I just have to write it from scratch, probably using reflection?
Thanks
Create userInfo class
type UserInfo struct {
ID string `json:"ID"`
Name string `json:"Name"`
Age int `json:"Age"`
Address struct {
City string `json:"city"`
Province string `json:"province"`
} `json:"address"`
}
Then unmarshal your json data into a userinfo object
var userInfo UserInfo
jsonStr := `{
"ID": "1",
"Name": "Keith Baldwin",
"Age": 30,
"address": {
"city": "Saskatoon",
"province": "Saskatchewan"
}
}`
json.Unmarshal([]byte(jsonStr), &userInfo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With