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 会在值为零时将其排除,而 int 的默认值为零。有什么方法可以省略条件中的字段(例如:如果值为 -1 则省略)。或者有什么办法可以做到。
最佳答案
您可以使用 *int
而不是 int 并将指针值设置为 nil 以省略它。
package main
import (
"encoding/json"
"fmt"
)
type MyStruct struct {
Code int `json:"Code"`
Flags uint8 `json:"Flags"`
OptionField *int `json:",omitempty"`
}
func format(s MyStruct) string {
r, _ := json.Marshal(s)
return string(r)
}
func main() {
f := MyStruct{Code: 500, Flags: 10, OptionField: new(int)}
fmt.Println(format(f)) // {"Code":500,"Flags":10,"OptionField":0}
f.OptionField = nil
fmt.Println(format(f)) // {"Code":500,"Flags":10}
}
关于go - 如何在编码(marshal)中省略结构的条件字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247098/