-
Notifications
You must be signed in to change notification settings - Fork 114
/
gojay_example_test.go
73 lines (61 loc) · 1.17 KB
/
gojay_example_test.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
64
65
66
67
68
69
70
71
72
73
package gojay_test
import (
"fmt"
"log"
"os"
"strings"
"github.com/francoispqt/gojay"
)
type User struct {
ID int
Name string
Email string
}
func (u *User) UnmarshalJSONObject(dec *gojay.Decoder, k string) error {
switch k {
case "id":
return dec.Int(&u.ID)
case "name":
return dec.String(&u.Name)
case "email":
return dec.String(&u.Email)
}
return nil
}
func (u *User) NKeys() int {
return 3
}
func (u *User) MarshalJSONObject(enc *gojay.Encoder) {
enc.IntKey("id", u.ID)
enc.StringKey("name", u.Name)
enc.StringKey("email", u.Email)
}
func (u *User) IsNil() bool {
return u == nil
}
func Example_decodeEncode() {
reader := strings.NewReader(`{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}`)
dec := gojay.BorrowDecoder(reader)
defer dec.Release()
u := &User{}
err := dec.Decode(u)
if err != nil {
log.Fatal(err)
}
enc := gojay.BorrowEncoder(os.Stdout)
err = enc.Encode(u)
if err != nil {
log.Fatal(err)
}
fmt.Printf("\nUser ID: %d\nName: %s\nEmail: %s\n",
u.ID, u.Name, u.Email)
// Output:
// {"id":1,"name":"John Doe","email":"[email protected]"}
// User ID: 1
// Name: John Doe
// Email: [email protected]
}