如何不使用 Go 将空结构编组到 JSON 中? [英] How to not marshal an empty struct into JSON with Go?
问题描述
我有一个这样的结构:
type Result struct {
Data MyStruct `json:"data,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
}
但即使 MyStruct 的实例完全为空(即所有值都是默认值),它也会被序列化为:
But even if the instance of MyStruct is entirely empty (meaning, all values are default), it's being serialized as:
"data":{}
我知道 encoding/json 文档指定空"字段是:
I know that the encoding/json docs specify that "empty" fields are:
false, 0, 任何 nil 指针或接口值,以及任何数组,切片、映射或长度为零的字符串
false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero
但不考虑具有所有空/默认值的结构.它的所有字段也都标有 omitempty
,但这没有任何效果.
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.
如何让 JSON 包不编组我的空结构字段?
How can I get the JSON package to not marshal my field that is an empty struct?
推荐答案
正如文档所说,任何 nil 指针".-- 使结构成为指针.指针有明显的空"值:nil
.
As the docs say, "any nil pointer." -- make the struct a pointer. Pointers have obvious "empty" values: nil
.
修复 - 使用结构指针字段定义类型:
Fix - define the type with a struct pointer field:
type Result struct {
Data *MyStruct `json:"data,omitempty"`
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
}
然后是这样的值:
result := Result{}
将编组为:
{}
说明:注意我们类型定义中的*MyStruct
.JSON 序列化不关心它是否是一个指针——这是一个运行时细节.所以将结构体字段变成指针只对编译和运行时有影响).
Explanation: Notice the *MyStruct
in our type definition. JSON serialization doesn't care whether it is a pointer or not -- that's a runtime detail. So making struct fields into pointers only has implications for compiling and runtime).
请注意,如果您确实将字段类型从 MyStruct
更改为 *MyStruct
,您将需要指向结构值的指针来填充它,如下所示:
Just note that if you do change the field type from MyStruct
to *MyStruct
, you will need pointers to struct values to populate it, like so:
Data: &MyStruct{ /* values */ }
这篇关于如何不使用 Go 将空结构编组到 JSON 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!