go: json marshal and unmarshal

发布时间 2023-09-01 15:46:14作者: nick_qiu

引用:

  https://bluehive.medium.com/golang-json-marshal-a-struct-with-pointers-2a362d0543f5

1. Golang JSON Marshal a Struct With Pointers:

  a. Always name member names in upper case: the lower case name is never marshalled

  b.golang marshaller can process nested struct with pointer fields

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.PNum)

}

//Output

<nil> data={"PNum":{"N":100},"Name":"xx-packed-xy"}
<nil> &{N:100}