优惠全部云服务器首月 8 折,优惠码 CLOUD去领取

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

· 阅读约 3 分钟

问题内容

我尝试理解为什么两个函数返回相同的输出。 据我了解,省略空的目的是不将该键添加到结果结构中。

我写了这个例子,我期望第一个输出没有“empty”键,但由于某种原因它的值仍然显示为 0。

package main

import (
    "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
}

解决方案

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

今天关于《如何使用 json.decoder 省略空 json 字段》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关文章

更多「网站和优化」文章服务器使用指南