我有一个结构:
type Paper struct {
PID int `json:"pID"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd"`
}
大多数情况下,我会将整个结构编码为 JSON。然而,偶尔,我需要 结构的简短版本;即编码一些属性,我应该如何实现这个功能?
type BriefPaper struct {
PID int `json:"-"` // not needed
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"-"` // not needed
}
我正在考虑创建一个子集结构,类似于 BriefPaper = SUBSET(Paper)
,但不确定如何在 Golang 中实现它。
我希望我能做这样的事情:
p := Paper{ /* ... */ }
pBrief := BriefPaper{}
pBrief = p;
p.MarshalJSON(); // if need full JSON, then marshal Paper
pBrief.MarshalJSON(); // else, only encode some of the required properties
这可能吗?
最佳答案
可能最简单的方法是创建一个嵌入 Paper
的结构,并隐藏要隐藏的字段:
type Paper struct {
PID int `json:"pID"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd"`
}
type BriefPaper struct {
Paper
PID int `json:"pID,omitempty"` // Just make sure you
PPwd string `json:"pPwd,omitempty"` // don't set these fields!
}
p := Paper{ /* ... */ }
pBrief := BriefPaper{Paper: p}
现在,当编码 BriefPaper
时,字段 PID
和 PPwd
将被省略。
关于go - 如何有选择地编码(marshal)结构的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982842/