gpt4 book ai didi

json - Golang jsonable 指向 slice 中不同结构的指针

转载 作者:IT王子 更新时间:2023-10-29 01:43:11 25 4
gpt4 key购买 nike

我的 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 的结构的指针?

最佳答案

您可以使用 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)
}

playground

关于json - Golang jsonable 指向 slice 中不同结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com