-
Notifications
You must be signed in to change notification settings - Fork 2
/
json_test.go
125 lines (117 loc) · 2.4 KB
/
json_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package lab27
import (
"encoding/json"
"fmt"
"testing"
)
var sampleJson = []byte(`
[
{
"kind":"dog",
"attr":{
"type":"Collie",
"color":"black"
}
},
{
"kind":"duck",
"attr":{
"weight":1.2
}
}
]
`)
type DogAttr struct {
Type string `json:"type"`
Color string `json:"color"`
}
type DuckAttr struct {
Weight float64
}
func TestDecodeFlexObject(t *testing.T) {
type Animal struct {
Kind string `json:"kind"`
Attr json.FlexObject `json:"attr"`
}
var animals []Animal
json.Unmarshal(sampleJson, &animals)
for i, v := range animals {
var d interface{}
switch v.Kind {
case "dog":
d = &DogAttr{}
case "duck":
d = &DuckAttr{}
default:
t.Fatalf("unsupport kind %s", v.Kind)
}
if err := v.Attr.DelayedUnmarshalJSON(d); err != nil { // delay decoding FlexObject
t.Fatal(err)
}
fmt.Printf("index %d, kind=%s attr=%#v\n", i, v.Kind, v.Attr.D)
}
// Output:
// index 0, kind=dog attr=&lab27.DogAttr{Type:"Collie", Color:"black"}
// index 1, kind=duck attr=&lab27.DuckAttr{Weight:1.2}
}
func TestFlexObjectFactory(t *testing.T) {
var factory = NewFactory()
factory.MustReg("dog", (*DogAttr)(nil))
factory.MustReg("duck", (*DuckAttr)(nil))
type Animal struct {
Kind string `json:"kind"`
Attr json.FlexObject `json:"attr"`
}
var animals []Animal
json.Unmarshal(sampleJson, &animals)
for i, v := range animals {
factory.DelayedFlexObjectJSONUnmarshal(v.Kind, &v.Attr)
fmt.Printf("index %d, kind=%s attr=%#v\n", i, v.Kind, v.Attr.D)
}
// Output:
// index 0, kind=dog attr=&lab27.DogAttr{Type:"Collie", Color:"black"}
// index 1, kind=duck attr=&lab27.DuckAttr{Weight:1.2}
}
func TestGenerateJsonByFlexObject(t *testing.T) {
type Animal struct {
Kind string `json:"kind"`
Attr json.FlexObject `json:"attr"`
}
var animals = []Animal{
Animal{
Kind: "dog",
Attr: json.FlexObject{
D: DogAttr{
Type: "Collie",
Color: "white",
},
},
},
Animal{
Kind: "duck",
Attr: json.FlexObject{
D: DuckAttr{
Weight: 2.34,
},
},
},
}
b, _ := json.MarshalIndent(animals, "", " ")
fmt.Println(string(b))
// Ooutput:
// [
// {
// "kind": "dog",
// "attr": {
// "type": "Collie",
// "color": "white"
// }
// },
// {
// "kind": "duck",
// "attr": {
// "Weight": 2.34
// }
// }
// ]
}