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

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


我写了这个例子,我期望第一个输出没有“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

}


温温酱
浏览 72回答 1
1回答

森林海

您需要定义 Empty ,*int以便在没有值时将其替换为 nil 。那么它就不会保存在数据库中。
打开App,查看更多内容
随时随地看视频慕课网APP