登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-28 11:18:25 199浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《如何使用 json.decoder 省略空 json 字段》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

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

我写了这个例子,我期望第一个输出没有“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 字段》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>