Golang JSON Marshal a Struct With Pointers
1 min readApr 17, 2021
package main
import (
"encoding/json"
"fmt"
)
type Num struct {
N int
}
type Packed struct {
pNum *Num
Name string
}
func main() {
num := &Num{N: 100}
packed := Packed{pNum: num, Name: "xx-packed-xy"}
dataInBytes, err := json.Marshal(packed)
fmt.Printf("%+v data=%s\n", err, string(dataInBytes))
unpacked := &Packed{}
err = json.Unmarshal(dataInBytes, unpacked)
fmt.Printf("%v, %+v\n", err, unpacked)
}
The above code marshals an object of type struct using a pointer. The code does not work as expected. That means the unmarshalled object does…