/
pointer.go
44 lines (36 loc) · 892 Bytes
/
pointer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package nulls
import (
"encoding/json"
"fmt"
)
// ExamplePointer is the same, but
// uses a *Int
type ExamplePointer struct {
Age *int `json:"age,omitempty"`
Name string `json:"name"`
}
// PointerEncoding shows methods for
// dealing with nil/omitted values
func PointerEncoding() error {
// note that no age = nil age
e := ExamplePointer{}
if err := json.Unmarshal([]byte(jsonBlob), &e); err != nil {
return err
}
fmt.Printf("Pointer Unmarshal, no age: %+v\n", e)
value, err := json.Marshal(&e)
if err != nil {
return err
}
fmt.Println("Pointer Marshal, with no age:", string(value))
if err := json.Unmarshal([]byte(fulljsonBlob), &e); err != nil {
return err
}
fmt.Printf("Pointer Unmarshal, with age = 0: %+v\n", e)
value, err = json.Marshal(&e)
if err != nil {
return err
}
fmt.Println("Pointer Marshal, with age = 0:", string(value))
return nil
}