【发布时间】:2018-11-11 08:41:25
【问题描述】:
有MyStruct的结构体。
type MyStruct struct {
Code int `json:"Code"`
Flags uint8 `json:"Flags"`
OptionField int `json:",omitempty"`
}
以下代码将其转换为 json。
f := MyStruct{Code:500, OptionField:41}
r, _ := json.Marshal(f)
fmt.Println(string(r)
我需要“OptionField”是可选的。有时它应该存在于 json 中,值为 [0, 1, 2, 3, ] 之一。而在其他时候它应该从 json 中排除。
我的问题是:omitempty在值为0的时候会排除,而int的默认值是0。有没有办法在条件中省略字段(例如:如果值为-1,则省略)。或者有什么办法。
【问题讨论】:
标签: go