gpt4 book ai didi

go - 用 omitempty 编码 sql.NullString

转载 作者:IT王子 更新时间:2023-10-29 00:40:39 28 4
gpt4 key购买 nike

如果 null sql.NullString 无效,应该如何不呈现它? - http://play.golang.org/p/pzSWS9vE0J

它似乎不能与 omitempty struct 标签一起工作,我不太清楚要从 MarshalJSON 返回什么,这样 omitempty 就会受到尊重

type NS struct {
sql.NullString
}

func (ns *NS) MarshalJSON() ([]byte, error) {
fmt.Println("Marshaling json for NS")
if ns.String == "" && !ns.Valid {
return []byte("null"), nil
}
return json.Marshal(ns.String)
}

type A struct {
RStr string `json:rstr,omitempty"`
Str NS `json:"str,omitempty"`
}


func main() {
a := A{RStr: "rstr"}
s, _ := json.Marshal(&a)
fmt.Println(string(s))
}

最佳答案

据我所知,没有办法做到这一点,但是您始终可以使用指针代替:http://play.golang.org/p/b4Q7YgpUa-

func main() {
a := A{"rstr", &sql.NullString{"Test", true}}
s, err := json.Marshal(&a)
fmt.Println(string(s), err)
a = A{}
fmt.Println(json.Unmarshal(s, &a))
fmt.Printf("%v %v\n", a.RStr, a.Str.String)
a = A{RStr: "rstr"}
s, err = json.Marshal(&a)
fmt.Println(string(s), err)
}

指针与http://tip.golang.org/pkg/encoding/json/#Marshal不同的原因:

-the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

关于go - 用 omitempty 编码 sql.NullString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24345621/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com