-
Notifications
You must be signed in to change notification settings - Fork 0
/
json1.go
54 lines (49 loc) · 991 Bytes
/
json1.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
package main
import (
"encoding/json"
"fmt"
"log"
)
type Actor struct {
Name string `json:"name"`
Age int `json:"age"`
}
type Movie struct {
Title string `json:"title"`
Year int `json:"year"`
Color bool `json:"color"`
Actors []Actor `json:"actors"`
}
func main() {
//结构体转json
movies := []Movie{
{
Title: "功夫",
Year: 1998,
Color: true,
Actors: []Actor{Actor{Name: "成龙", Age: 53}, Actor{Name: "王宝强", Age: 33}},
},
{
Title: "僵尸先生",
Year: 1999,
Color: true,
Actors: []Actor{Actor{Name: "林正英", Age: 43}, Actor{Name: "范冰冰", Age: 33}},
},
}
//if便捷写法
/* if data, err := json.Marshal(movies); err == nil {
fmt.Printf("%s\n", data)
}
*/ if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", data)
//json转结构体
var data2 []Movie
//var data2 []struct{ Title string }
err2 := json.Unmarshal(data, &data2)
if err != nil {
log.Fatal(err2)
}
fmt.Println(data2)
}