json tag type
- json tag type用于struct marshal/unmarshal时,将结构体字段按照一定规则,转换为json字段,如下文,Project结构体,marshal后"Name"转换为"name"
type Project struct { Name string `json:"name"` Id string `json:"id"` }
- 基本格式: Name(定义的字段名) string(类型)
json:"opt1,opt2" key:"value"
tag:inline
- 常用语内嵌结构体
- 未定义inline时,如下输出:
输出:type Project struct { Name string `json:"name"` Id string `json:"id"` } type ProjectList struct { Project `json:"project"` Description string `json:"description"` } func main() { p := Project{ Name: "projectA", Id: "xxx01", } pL := ProjectList{ p, "Has one Project", } body, _ := json.Marshal(pL) fmt.Printf("marshal body is: %v\n", string(body)) }
D:\restfulAPIPractise>go run main.go marshal body is: {"project":{"name":"projectA","id":"xxx01"},"description":"Has one Project"}
- 定义
json:",inline"
时:
如将上文做一下变更:
输出:type ProjectList struct { Project `json:",inline"` // 变更点 Description string `json:"description"` }
D:\restfulAPIPractise>go run main.go marshal body is: {"name":"projectA","id":"xxx01","description":"Has one Project"}
type:omitempty
- omitempty,当字段值为空时,忽略
输出,description为空值,输出不显示:type ProjectList struct { Project `json:"project"` Description string `json:"description,omitempty"` // omitempty }
marshal body is: {"project":{"name":"projectA","id":"xxx01"}}
- 对比,当不设置omitempty时
输出:type ProjectList struct { Project `json:"project"` Description string `json:"description"` // 未设置omitempty }
marshal body is: {"project":{"name":"projectA","id":"xxx01"},"description":""}
tag: -
- json:“-”,忽略,即便字段有值
输出:type ProjectList struct { Project `json:"project"` Description string `json:"-"` // } // main中 pL := ProjectList{ p, "xxx happy", // description有值 }
marshal body is: {"project":{"name":"projectA","id":"xxx01"}}