Asaelko
Asaelko

Reputation: 88

Golang jsonable pointers to different structs in slice

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?

Upvotes: 2

Views: 1117

Answers (1)

OneOfOne
OneOfOne

Reputation: 99224

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

playground

Upvotes: 3

Related Questions