英文:
Golang jsonable pointers to different structs in slice
问题
我的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数组中。使用Reflect
返回结构体的指针,我将它们附加到结构体中,但是encoding/json
包在结果JSON中将指针替换为整数地址。此外,unsafe.Pointer
也无法被encoding/json
解析。
我希望最终的JSON结果如下所示:
{
"count": 2,
"objects": [
{"FieldA": "..."},
{"FieldB": "..."}
]
}
我该如何存储指向结构体的指针,以便正确编码为JSON?
英文:
My golang program have this structure of structs:
type JSONDoc struct {
Count int `json:"count"`
Objects []uintptr `json:"objects"`
}
type ObjectA struct {
FieldA string
}
type ObjectB struct {
FieldB string
}
I don't know what object types can be in JSONDoc.Objects, i'm need to store multiple structs in json array. Reflect
returns pointers to structs, i'm appending them to struct, but encoding/json
package in result json replace pointer with integer address.
Also unsafe.Pointer cannot be parsed by encoding/json
too.
Just want result json to look as
{
"count":2,
"objects":
[
{"FieldA":"..."},
{"FieldB":"..."}
]
}
How can i store pointers to structs that will be correctly encoded to json?
答案1
得分: 3
你可以使用interface{}
,例如:
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)
}
英文:
You could use interface{}
, for example :
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论