草庐IT

MarshalJSON

全部标签

json - 我可以使用 MarshalJSON 将任意字段添加到 golang 中的 json 编码吗?

假设我编写了以下代码片段。Playground上的完整代码here适合那些喜欢的人。typeBookstruct{TitlestringAuthorstring}funcmain(){ms:=Book{"Catch-22","JosephHeller"}out,err:=json.MarshalIndent(ms,"","")iferr!=nil{log.Fatalln(err)}fmt.Println(string(out))}此代码输出以下内容,完全符合我的预期:{"Title":"Catch-22","Author":"JosephHeller"}假设我想在JSON输出中添加一个

json - 自定义 MarshalJSON() 永远不会在 Go 中被调用

我编写了MarshalJSON和UnmarshalJSON的自定义版本。我的UnmarshalJSON以我想要的方式被调用,但我无法让它与MarshalJSON一起工作。这是总结我的问题的代码:packagemainimport("bytes""encoding/json""fmt""log""os")typemyStructstruct{Datastring`json:"data"`}func(s*myStruct)MarshalJSON()([]byte,error){return[]byte(`{"data":"charlie"}`),nil}func(s*myStruct)Un