英文:
json.Unmarshal convert to custom another type (map to slice)
问题
给定以下JSON字符串:
{
"username":"bob",
"name":"Robert",
"locations": [
{
"city": "Paris",
"country": "France"
},
{
"city": "Los Angeles",
"country": "US"
}
]
}
我需要一种将其解组成以下结构的方法:
type User struct {
Username string
Name string
Cities []string
}
其中Cities
是一个包含"city"值的切片,而"country"被丢弃。
我认为可以使用自定义的JSON.Unmarshal
函数来实现,但不确定如何做到这一点。
英文:
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.
答案1
得分: 3
你可以为Cities
定义新的类型,并实现自定义的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
}
<kbd>PLAYGROUND</kbd>
英文:
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
}
<kbd>PLAYGROUND</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论