英文:
How to ignore empty fields when using json.Marshal on an external Go struct?
问题
我有一个在外部包中定义的struct
(即我无法控制此struct
)。当我使用json.Marshal
将其转换为JSON字符串时,未设置的字段会被包含为null
。我该如何编组它,以便忽略未设置的字段?例如:
外部struct
(我无法修改它!):
type ExternalStruct struct {
Success bool
Details *string
}
在我的代码中:
import "external/package/providing/external/struct"
import "encoding/json"
...
result := ExternalStruct{Success: true}
resultJson, _ := json.Marshal(result)
println(string(resultJson))
返回:
{"Success": true, "Details": null}
但我想要的是:
{"Success": true}
如果可能的话,我希望找到一种不依赖于了解externalStruct
内部结构的解决方案,因为我有几个受此影响的外部struct
,所以理想情况下,我希望有一段代码可以将它们编组,同时忽略任何未设置的字段。其中一些struct
还包含嵌套的struct
。
英文:
I have a struct
defined in an external package (i.e. I have no control over this struct). When I use json.Marshal
to convert it into a json string, the fields that are not set are included as null
. How can I marshal it so that the unset fields are ignored? For example:
External struct (I can't modify this!):
type ExternalStruct struct {
Success bool
Details *string
}
In my code:
import "external/package/providing/external/struct"
import "encoding/json"
...
result := ExternalStruct{Success: true}
resultJson, _ := json.Marshal(result)
println(string(resultJson))
returns:
{"Success": true, "Details": null}
but I want:
{"Success": true}
I'm looking for a solution that does not rely on knowing the internals of externalStruct
, if at all possible, because I have several external structs affected by this, so ideally I would like to have a single piece of code that can marshal them while ignoring any unset fields. Some of the structs have nested structs too.
答案1
得分: 2
当你想要控制合同(数据如何编组)时,我建议不要依赖于可能在没有通知的情况下发生变化的外部结构。相反,创建自己的结构并复制字段。
英文:
When you want to control the contract (hhow data is marshaled) I'd suggest not relying on external struct that can change without notice. Instead create your own struct and copy the fields.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论