为了账号安全,请及时绑定邮箱和手机立即绑定

将 null 分配给 JSON 字段而不是空字符串

将 null 分配给 JSON 字段而不是空字符串

Go
拉风的咖菲猫 2021-10-18 14:21:41
由于空字符串是 Go 的零/默认值string,因此我决定将所有此类字段定义为interface{}。例如type student struct {    FirstName  interface{} `json:"first_name"`    MiddleName interface{} `json:"middle_name"`    LastName   interface{} `json:"last_name"`}如果该特定字段的值不可用,我发送数据的应用程序需要一个 null 而不是空字符串。这是正确的方法还是有人可以指出我比这更好的方法。
查看完整描述

3 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

在json 包文档中:


指针值编码为指向的值。空指针编码为空 JSON 对象。


所以你可以存储一个指向字符串的指针,如果不是 nil,它将被编码为一个字符串,如果 nil 将被编码为“null”


type student struct {

  FirstName  *string `json:"first_name"`

  MiddleName *string `json:"middle_name"`

  LastName   *string `json:"last_name"`

}


查看完整回答
反对 回复 2021-10-18
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

另一种方法实际上是使用 golang 的 json 库提供的 MarhshalJSON 和 UnmarshalJSON 接口方法的解决方法。代码如下:


type MyType string

type MyStruct struct {

    A MyType `json:"my_type"`

}


func (c MyType) MarshalJSON() ([]byte, error) {

    var buf bytes.Buffer

    if len(string(c)) == 0 {

        buf.WriteString(`null`)

    } else {

        buf.WriteString(`"` + string(c) + `"`)   // add double quation mark as json format required

    }

    return buf.Bytes(), nil

}


func (c *MyType)UnmarshalJSON(in []byte) error {

    str := string(in)

    if str == `null` {

        *c = ""

        return nil

    }

    res := MyType(str)

    if len(res) >= 2 {

        res = res[1:len(res)-1]     // remove the wrapped qutation

    }

    *c = res

    return nil

}

那么当使用 json.Marshal 时,MyType 值将被编组为 null。


查看完整回答
反对 回复 2021-10-18
  • 3 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信