JSON 是一个布尔省略

我在为 api 编写 golang 库时遇到问题。布尔值的 json 方面导致了问题。

假设对于 api 调用,布尔值的默认值为 true。

如果我做

SomeValue bool `json:some_value,omitempty`

而且我没有通过库设置值,该值将设置为true。如果我在库中将该值设置为 false,则 omitempty 表示 false 值是一个空值,因此该值将通过 api 调用保持为真。

让我们去掉省略号,让它看起来像这样

SomeValue bool `json:some_value`

现在我遇到了相反的问题,我可以将值设置为 false,但如果我不设置该值,那么即使我希望它为 true,该值也会为 false。

编辑:如何保持不必将值设置为 true 同时也能够将值设置为 false 的行为?


守候你守候我
浏览 185回答 1
1回答

忽然笑

使用指针package mainimport (    "encoding/json"    "fmt")type SomeStruct struct {    SomeValue *bool `json:"some_value,omitempty"`}func main() {    t := new(bool)    f := new(bool)    *t = true    *f = false    s1, _ := json.Marshal(SomeStruct{nil})    s2, _ := json.Marshal(SomeStruct{t})    s3, _ := json.Marshal(SomeStruct{f})    fmt.Println(string(s1))    fmt.Println(string(s2))    fmt.Println(string(s3))}输出:{}{"some_value":true}{"some_value":false}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go