Json Golang Jsable指向切片中不同结构的指针
我的golang程序具有以下结构:Json Golang Jsable指向切片中不同结构的指针,json,pointers,struct,go,Json,Pointers,Struct,Go,我的golang程序具有以下结构: type JSONDoc struct { Count int `json:"count"` Objects []uintptr `json:"objects"` } type ObjectA struct { FieldA string } type ObjectB struct { FieldB string } 我不知道JSONDoc.Objects中可以有什么对象类型,我需要在json数
type JSONDoc struct {
Count int `json:"count"`
Objects []uintptr `json:"objects"`
}
type ObjectA struct {
FieldA string
}
type ObjectB struct {
FieldB string
}
我不知道JSONDoc.Objects中可以有什么对象类型,我需要在json数组中存储多个结构Reflect
返回指向struct的指针,我将它们附加到struct,但结果中的encoding/json
包用整数地址替换指针。
同样不安全。指针也不能被编码/json
解析
只希望结果json看起来像
{
"count":2,
"objects":
[
{"FieldA":"..."},
{"FieldB":"..."}
]
}
如何存储指向将正确编码为json的结构的指针?您可以使用
接口{}
,例如:
type JSONDoc struct {
Count int `json:"count"`
Objects []interface{} `json:"objects"`
}
func main() {
doc := JSONDoc{Count: 2}
doc.Objects = append(doc.Objects, &ObjectA{"A"}, &ObjectB{"B"})
b, err := json.MarshalIndent(&doc, "", "\t")
fmt.Println(string(b), err)
}