Golang中切片中指向不同结构体的可JSON化指针

huangapple go评论68阅读模式
英文:

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)
}

playground

英文:

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)
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2014年7月12日 04:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/24706034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定