在omitempty标签中,即使是空的结构体也会被获取到。

huangapple go评论64阅读模式
英文:

Got empty struct even in omitempty tag

问题

我已经使用相同的结构体在主结构体中内联和嵌套使用,并使用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

英文:

I have used the same struct for inline and nested in the main struct with omitempty tag. Since I'm not assigning any values in the keys I get the empty struct in JSON. Can anyone help me in this case?

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))
}

Output:

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

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

答案1

得分: 1

'omitempty'是在字段值为空时省略该字段。但在Golang中,我们没有结构体的空值,你可以使用指向结构体的指针(在你的情况下是*Zone)来代替。

...

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

...
英文:

'omitempty' is omit a field if the field value is empty. But in Golang we do not have empty value for struct and you can use pointer to struct (in your case *Zone) instead.

...

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

...

huangapple
  • 本文由 发表于 2022年1月22日 21:32:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70813330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定