-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSON.go
83 lines (69 loc) · 1.34 KB
/
JSON.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
/*
JSON
本代码旨在对JSON编码解码进行测试
*/
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Name Name
Email []Email
}
type Name struct {
Family string
Personal string
}
type Email struct {
Kind string
Address string
}
// Person的toString方法
func (p Person) String() string {
s := p.Name.Personal + " " + p.Name.Family
for _, v := range p.Email {
s += "\n" + v.Kind + ": " + v.Address
}
return s
}
func main() {
fileName := "person.json"
saveJson(fileName)
var person Person
loadJSON(fileName, &person)
fmt.Println("Person", person.String())
}
func saveJson(fileName string) {
person := Person{
Name: Name{Family: "Chu", Personal: "Tian Le"},
Email: []Email{
Email{Kind: "Work", Address: "[email protected]"},
Email{Kind: "Life", Address: "[email protected]"},
},
}
// 创建文件
outFile, err := os.Create(fileName)
checkError(err)
// 编码写入
encoder := json.NewEncoder(outFile)
err = encoder.Encode(person)
checkError(err)
// 关闭文件
outFile.Close()
}
func loadJSON(fileName string, key interface{}) {
inFile, err := os.Open(fileName)
checkError(err)
decoder := json.NewDecoder(inFile)
err = decoder.Decode(key)
checkError(err)
inFile.Close()
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}