如何不使用Go将一个空的结构编组到JSON中? [英] How to not marshal an empty struct into JSON with Go?
问题描述
type结果struct {
Data MyStruct`json:data, omitempty`
状态字符串`json:status,omitempty`
原因字符串`json:reason,omitempty`
}
但即使MyStruct的实例完全为空(意思是所有值都是默认值),它都会被序列化为:
data:{}
我知道编码/ json 文档指定空白字段为:
false,0,任何nil指针或接口值,以及任何数组,
slice,map或长度为零的字符串
但没有考虑具有所有空/默认值的结构。它的所有字段也被标记为 omitempty
,但这没有效果。
如何获取JSON包到不是编组我的字段是一个空的结构体?
轻松修复:任何零指针。 - 使结构成为一个指针。
修正:
类型结果struct {
Data * MyStruct`json:data,omitempty`
状态字符串`json:status,omitempty`
原因字符串`json:reason,omitempty`
注意 * MyStruct
- 当我现在创建一个 MyStruct
时,我只需引用即可:
myStruct:=& MyStruct {/ * values * /}
现在空 MyStruct
不再按照需要编组成JSON。
I have a struct like this:
type Result struct {
Data MyStruct `json:"data,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
}
But even if the instance of MyStruct is entirely empty (meaning, all values are default), it's being serialized as:
"data":{}
I know that the encoding/json docs specify that "empty" fields are:
false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero
but with no consideration for a struct with all empty/default values. All of its fields are also tagged with omitempty
, but this has no effect.
How can I get the JSON package to not marshal my field that is an empty struct?
Oh! Easy fix: "any nil pointer." -- make the struct a pointer.
Fix:
type Result struct {
Data *MyStruct `json:"data,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
}
Notice the *MyStruct
-- when I create a MyStruct
now, I simply do so by reference:
myStruct := &MyStruct{ /* values */ }
And now the "empty" MyStruct
is no longer marshaled into JSON as desired.
这篇关于如何不使用Go将一个空的结构编组到JSON中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!