[英]How to show empty object instead of empty struct or nil in Go json marshal
I need to show json's empty object {}
when do json.Marshal()
for a struct pointer. 当
json.Marshal()
用于结构指针时,我需要显示json的空对象{}
。 I can only output either null
value or empty struct value. 我只能输出
null
值或空结构值。
If the person
key is filled with &Person{}
or new(Person)
, it will show empty struct like below: 如果
person
键用&Person{}
或new(Person)
填充,它将显示如下的空结构:
{
"data": {
"person": {
"name": "",
"age": 0
},
"created_date": "2009-11-10T23:00:00Z"
}
}
And if we don't initialize it at all, it will show null
. 如果我们根本不初始化它,它将显示为
null
。
{
"data": {
"person": null,
"created_date": "2009-11-10T23:00:00Z"
}
}
I want to show "person": {}
. 我想表现出
"person": {}
。 Is it possible? 可能吗?
Go Playground for the complete code: https://play.golang.org/p/tT15G2ESPVc 去游乐场获取完整代码: https : //play.golang.org/p/tT15G2ESPVc
Option A , use the omitempty
tag option on all of the Person
's fields and make sure the response's field is allocated before marshaling. 选项A ,在所有
Person
的字段上使用omitempty
标签选项,并确保在编组之前分配响应的字段。
type Person struct {
Name string `json:"name,omitempty"`
Age int `json:"age,omitempty"`
}
// ...
resp.Person = new(Person)
https://play.golang.org/p/o3jWdru_8bC https://play.golang.org/p/o3jWdru_8bC
Option B , use a non-pointer wrapper type that embeds the Person
pointer type. 选项B ,使用嵌入
Person
指针类型的非指针包装器类型。
type PersonJSON struct {
*Person
}
type Response struct {
Person PersonJSON `json:"person"`
CreatedDate time.Time `json:"created_date"`
}
https://play.golang.org/p/EKQc7uf1_Vk https://play.golang.org/p/EKQc7uf1_Vk
Option C , have the Reponse
type implement the json.Marshaler
interface. 选项C,有
Reponse
类型实现json.Marshaler
接口。
func (r *Response) MarshalJSON() ([]byte, error) {
type tmp Response
resp := (*tmp)(r)
var data struct {
Wrapper struct {
*Person
} `json:"person"`
*tmp
}
data.Wrapper.Person = resp.Person
data.tmp = resp
return json.Marshal(data)
}
https://play.golang.org/p/1qkSCWZ225j https://play.golang.org/p/1qkSCWZ225j
There may be other options... 可能还有其他选择......
In Go, an empty struct by definition assigns zero values to field elements. 在Go中,根据定义,空结构为字段元素分配零值。 Eg: for int 0, "" for string, etc.
例如:对于int 0,“”表示字符串等。
For your case, simply comparing to null would work out. 对于您的情况,只需比较null即可。 Or, you could define an emptyPerson as:
或者,您可以将emptyPerson定义为:
var BAD_AGE = -1
emptyPerson := &Person{"", BAD_AGE} // BAD_AGE indicates no person
if person[age] == BAD_AGE {
// handle case for emptyPerson}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.