forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example4.go
51 lines (41 loc) · 1020 Bytes
/
example4.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show how write a custom Unmarshal and Marshal functions.
package main
import (
"encoding/json"
"fmt"
"time"
)
// NullableTime represents a nullable time for our sample.
type NullableTime struct {
time.Time
}
// MarshalJSON implements the Marshaler interface.
func (t NullableTime) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte(`null`), nil
}
return []byte(`"` + t.Format(time.RFC3339) + `"`), nil
}
// UnmarshalJSON implements the Unmarshaler interface.
func (t *NullableTime) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
t.Time = time.Time{}
return nil
}
tt, err := time.Parse(`"`+time.RFC3339+`"`, string(b))
if err != nil {
return err
}
t.Time = tt
return nil
}
func main() {
var n NullableTime
if err := json.Unmarshal([]byte("null"), &n); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v", n)
}