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

如何使用 json.decoder 省略空 json 字段

如何使用 json.decoder 省略空 json 字段

Go
温温酱 2023-08-14 14:38:58
我尝试理解为什么两个函数返回相同的输出。据我了解,省略空的目的是不将该键添加到结果结构中。我写了这个例子,我期望第一个输出没有“Empty”键,但由于某种原因它的值仍然显示为 0。package mainimport (    "encoding/json"    "fmt"    "strings")type agentOmitEmpty struct {    Alias   string `json:"Alias,omitempty"`    Skilled bool   `json:"Skilled,omitempty"`    FinID   int32  `json:"FinId,omitempty"`    Empty   int    `json:"Empty,omitempty"`}type agent struct {    Alias   string `json:"Alias"`    Skilled bool   `json:"Skilled"`    FinID   int32  `json:"FinId"`    Empty   int    `json:"Empty"`}func main() {    jsonString := `{        "Alias":"Robert",        "Skilled":true,        "FinId":12345    }`    fmt.Printf("output with omit emtpy: %v\n", withEmpty(strings.NewReader(jsonString)))    // output with omit emtpy: {Robert true 12345 0}    fmt.Printf("output regular: %v\n", withoutEmpty(strings.NewReader(jsonString)))    // output without omit: {Robert true 12345 0}}func withEmpty(r *strings.Reader) agentOmitEmpty {    dec := json.NewDecoder(r)    body := agentOmitEmpty{}    err := dec.Decode(&body)    if err != nil {        panic(err)    }    return body}func withoutEmpty(r *strings.Reader) agent {    dec := json.NewDecoder(r)    body := agent{}    err := dec.Decode(&body)    if err != nil {        panic(err)    }    return body}
查看完整描述

1 回答

?
森林海

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

您需要定义 Empty ,*int以便在没有值时将其替换为 nil 。那么它就不会保存在数据库中。



查看完整回答
反对 回复 2023-08-14
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

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