我在为 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 的行为?
1 回答

忽然笑
TA贡献1806条经验 获得超5个赞
使用指针
package main
import (
"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}
- 1 回答
- 0 关注
- 184 浏览
添加回答
举报
0/150
提交
取消