对于 json 和 struct 之间的转换,tag可以使json中字段与struct中字段名称解耦
type address struct {
Street string `json:"street"` // 街道
Ste string `json:"suite"` // 单元(可以不存在)
City string `json:"city"` // 城市
State string `json:"state"` // 州/省
Zipcode string `json:"zipcode"` // 邮编
}
对于上述结构体,每个字段在Unmarshal时候会找josn中对应tag的字段;
但是对于Marshal有一些值得注意的点 对于如下结构体address来UnMarshal到json
{
"Street": "200 Larkin St",
"City": "San Francisco",
"State": "CA",
"Zipcode": "94102"
}
输出如下
`{
"street": "200 Larkin St",
"city": "San Francisco",
"suite": "",
"state": "CA",
"zipcode": "94102"
}`
多了一行"suite":"",对此,在tag后加上omitempty来选择空值时不会包含默认值
陷阱
omitempty 无法忽略结构体
type address struct {
Street string `json:"street"`
Ste string `json:"suite,omitempty"`
City string `json:"city"`
State string `json:"state"`
Zipcode string `json:"zipcode"`
Coordinate coordinate `json:"coordinate,omitempty"`
}
type coordinate struct {
Lat float64 `json:"latitude"`
Lng float64 `json:"longitude"`
}
如果没有设置coordinate字段,结构体转json打印出来发现
{
"street": "200 Larkin St",
"city": "San Francisco",
"state": "CA",
"zipcode": "94102",
"coordinate": {
"latitude": 0,
"longitude": 0
}
}
解决方法就是把coordinate结构体设置为指针
同理,一些基本类型想要设置零值(比如int 0)时候omitempty在也会Unmarshal时候也会丢掉这个字段,这时候设置为指针类型就好了