dqrnsg6439 2017-09-27 15:23 采纳率: 100%
浏览 162

使用omitempty将嵌套结构中的0 / False编组到json

When marshalling a struct to JSON I am able to assign a variable to it's corresponding "empty value" and still pass it even when using omitempty, however I am unable to achieve the same result in a nested struct as it get's omitted despite being a pointer. Is this possible?

type Foo struct {
    Bar Bar `json:"bar,omitempty"`
    A *int  `json:"a,omitempty"`  //Does not get omitted when a = 0
    B *bool `json:"b,omitempty"`  //Does not get omitted when b = false
}

type Bar struct {
    X *int  `json:"x,omitempty"`  //Gets omitted when x = 0
    Y *bool `json:"y,omitempty"` //Gets omitted when y = false
}
  • 写回答

1条回答 默认 最新

  • doushi3202 2017-09-27 15:48
    关注

    Thats because they aren't empty.. You are setting them to 0/false. 0/false doesn't mean that they aren't there, you've given then a space in memory by assigning them a value.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Foo struct {
        Bar Bar   `json:"bar,omitempty"`
        A   *int  `json:"a,omitempty"` //Does not get omitted when a = 0
        B   *bool `json:"b,omitempty"` //Does not get omitted when b = false
    }
    
    type Bar struct {
        X *int  `json:"x,omitempty"` //Gets omitted when x = 0
        Y *bool `json:"y,omitempty"` //Gets omitted when y = false
    }
    
    func main() {
        var obj Foo
        a := 0 // a will not be not empty, it's set to 0
        obj.A = &a
    
        b, _ := json.MarshalIndent(obj, "", " ")
        fmt.Println(string(b))
    
        var obj2 Foo
        // a and everything else will be empty, nothing is set
    
        b, _ = json.MarshalIndent(obj2, "", " ")
        fmt.Println(string(b))
    }
    

    From the documentation

    The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

    The wording could be better, but empty in this case means that nothing has been assigned to that field. It doesn't mean if the field is literally set to 0 or false it will be empty. False and 0 are values as well and if you assign them then the field becomes 0 or false.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值