Go 如何有选择地封送结构的JSON?
我有一个结构:Go 如何有选择地封送结构的JSON?,go,Go,我有一个结构: type Paper struct { PID int `json:"pID"` PTitle string `json:"pTitle"` PDesc string `json:"pDesc"` PPwd string `json:"pPwd"` } 大多数情况下,我会将整个结构编码为JSON。然而,偶尔,我需要 结构的简要版本;i、 e.对某些属性进行编码,我应该如何实现此功能 type BriefPaper struct
type Paper struct {
PID int `json:"pID"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd"`
}
大多数情况下,我会将整个结构编码为JSON。然而,偶尔,我需要
结构的简要版本;i、 e.对某些属性进行编码,我应该如何实现此功能
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
可能吗 你为什么要这样做
type SubPaper struct {
PID int `json:"pID"`
PPwd string `json:"pPwd"`
}
如果你想得到完整的答复,那么就封送论文
子纸张选择性的事情可能最简单的方法是创建一个结构嵌入
纸张
,并隐藏要隐藏的字段:
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}
现在,当marshaing
公文包时,字段PID
和PPwd
将被省略。使用ommitempty in标记。创建结构实例时,无需指定要包括的项
type Paper struct {
PID int `json:"pID,omitempty"`
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
PPwd string `json:"pPwd,omitempty"`
}
func main() {
u := Paper{PTitle: "Title 1", PDesc: "Desc 1"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
打印:{“pTitle”:“标题1”,“pDesc”:“说明1”}
唯一的问题是,若PID显式为0,那个么它仍然会忽略它
比如:
论文{PTitle:“标题1”,PDesc:“说明1”,PID:0}
然后它仍然会打印{“pTitle”:“Title 1”,“pDesc”:“Desc 1”}
使用嵌入式类型执行此操作的另一种方法:
请注意,嵌入类型必须是指针,以便它可以是nil,然后可以将其排除在外
type Paper struct {
PID int `json:"pID"`
PPwd string `json:"pPwd"`
}
type BriefPaper struct {
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
*Paper `json:",omitempty"`
}
func main() {
u := BriefPaper{PTitle: "Title 1", PDesc: "Desc 1"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}
打印:{“pTitle”:“标题1”,“pDesc”:“说明1”}
如果需要纸张的嵌套内部结构,请将其标记为*paperjson:“paper,省略empty”
,但如何交换结构,例如subPaper=paper
?我能直接分配它吗?我不明白你们关于交换的说法,但你们可以使用像这样的接口var sub-interface{}
,然后像这样分配sub=SubPaper{}
或sub=Paper{}
接口将解决你们的问题。但我不知道你的确切问题是什么?不,在这种情况下你不能直接分配它。这种方法肯定会奏效,但使用起来很麻烦。纠正了,没看到。需要嵌入式指针类型。如果您想要嵌套的内部结构,请将其标记为*Paperjson:“Paper,ommitempty”
这种方法实际上根本不起作用。看见我很确定嵌入值上的json标记根本没有效果。如果为空,则表示省略。所以在这种情况下,inner必须为零。我用的方法。我知道省略空是什么意思。这与json标记在嵌入式结构上是否有任何意义无关。另请参见:它看起来确实会产生影响:但这仍然无助于OP的情况。
type Paper struct {
PID int `json:"pID"`
PPwd string `json:"pPwd"`
}
type BriefPaper struct {
PTitle string `json:"pTitle"`
PDesc string `json:"pDesc"`
*Paper `json:",omitempty"`
}
func main() {
u := BriefPaper{PTitle: "Title 1", PDesc: "Desc 1"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
}