JSON golang boolean omitempty

时间:2016-06-10 19:57:09

标签: json go

我在为api编写golang库时遇到问题。布林的json方面正在引发问题。

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

如果我这样做

SomeValue bool `json:some_value,omitempty`

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

让我们取出omitempty并让它看起来像这样

SomeValue bool `json:some_value`

现在我有相反的问题,我可以将值设置为false但是如果我没有设置值,那么即使我认为它是真的,该值也将为false。

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

1 个答案:

答案 0 :(得分:26)

Use pointers

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}