英文:
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":{}}
答案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"`
}
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论