如何在使用json.Marshal对外部Go结构进行序列化时忽略空字段?

huangapple go评论85阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年7月31日 15:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73181457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定