/
nullencoding.go
63 lines (52 loc) · 1.24 KB
/
nullencoding.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package nulls
import (
"database/sql"
"encoding/json"
"fmt"
)
type nullInt64 sql.NullInt64
// ExampleNullInt is the same, but
// uses a sql.NullInt64
type ExampleNullInt struct {
Age *nullInt64 `json:"age,omitempty"`
Name string `json:"name"`
}
func (v *nullInt64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Int64)
}
return json.Marshal(nil)
}
func (v *nullInt64) UnmarshalJSON(b []byte) error {
v.Valid = false
if b != nil {
v.Valid = true
return json.Unmarshal(b, &v.Int64)
}
return nil
}
// NullEncoding shows an alternative method
// for dealing with nil/omitted values
func NullEncoding() error {
e := ExampleNullInt{}
// note that no means an invalid value
if err := json.Unmarshal([]byte(jsonBlob), &e); err != nil {
return err
}
fmt.Printf("nullInt64 Unmarshal, no age: %+v\n", e)
value, err := json.Marshal(&e)
if err != nil {
return err
}
fmt.Println("nullInt64 Marshal, with no age:", string(value))
if err := json.Unmarshal([]byte(fulljsonBlob), &e); err != nil {
return err
}
fmt.Printf("nullInt64 Unmarshal, with age = 0: %+v\n", e)
value, err = json.Marshal(&e)
if err != nil {
return err
}
fmt.Println("nullInt64 Marshal, with age = 0:", string(value))
return nil
}