【问题标题】:Got empty struct even in omitempty tag [closed]即使在省略标签中也有空结构[关闭]
【发布时间】:2022-01-22 13:32:25
【问题描述】:

我对内联使用了相同的结构,并使用 omitempty 标记嵌套在主结构中。由于我没有在键中分配任何值,因此我在 JSON 中得到了空结构。在这种情况下有人可以帮助我吗?

package main

import (
    "encoding/json"
    "fmt"
)

type Customer struct {
    Name              string `json:"name,omitempty" bson:"name"`
    Gender            string `json:"gender,omitempty" bson:"gender"`
    Address           `json:",inline" bson:",inline" `
    OptionalAddresses []Address `json:"optionalAddresses,omitempty" bson:"optionalAddresses"`
}

type Address struct {
    Country    string `json:"country,omitempty" bson:"country"`
    ZoneDetail Zone   `json:"zone,omitempty" bson:"zone"`
}

type Zone struct {
    Latitude  float64 `json:"lat,omitempty" bson:"lat,omitempty"`
    Longitude float64 `json:"lon,omitempty" bson:"lon,omitempty"`
}

func main() {
    cust := Customer{Name: "abc", Gender: "M"}

    dataByt, _ := json.Marshal(cust)
    fmt.Println(string(dataByt))
}

输出:

{"name":"abc","gender":"M","zone":{}}

https://go.dev/play/p/aOlbwWelBS3

【问题讨论】:

  • 您能否将您期望的输出添加到您的问题中?
  • 空结构体依然存在,使用指针代替:ZoneDetail *Zone
  • 按文档工作。有什么问题?

标签: json go marshalling


【解决方案1】:

'omitempty' 如果字段值为空,则省略字段。但是在 Golang 中,我们没有 struct 的空值,您可以使用指向 struct 的指针(在您的情况下为 *Zone)。

...

type Address struct {
    Country    string `json:"country,omitempty" bson:"country"`
    ZoneDetail *Zone   `json:"zone,omitempty" bson:"zone"`
}

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多