JSON序列化
package main
import (
"encoding/json"
"fmt"
)
type Monster struct {
Name string
Age int `json:"age"`
Score float64
}
func testStruct() {
monster := Monster{Name: "牛魔王", Age: 300, Score: 95}
data, err := json.Marshal(&monster)
if err != nil {
fmt.Printf("序列化错误err=%v", err)
}
fmt.Printf("序列化结构体=%v\n", string(data))
}
func testSlice() {
var monster []map[string]interface{}
a := make(map[string]interface{})
a["name"] = "狮子精"
a["age"] = "320"
a["score"] = 92.5
b := make(map[string]interface{})
b["name"] = "大象精"
b["age"] = "560"
b["score"] = 90
monster = append(monster, a, b)
data, err := json.Marshal(monster)
if err != nil {
fmt.Printf("序列化错误err=%v", err)
}
fmt.Printf("序列化切片=%v\n", string(data))
}
func testMap() {
var monster map[string]interface{}
monster = make(map[string]interface{})
monster["name"] = "白骨精"
monster["age"] = 300
monster["score"] = 95.5
data, err := json.Marshal(monster)
if err != nil {
fmt.Printf("序列化错误err=%v", err)
}
fmt.Printf("序列化map=%v\n", string(data))
}
func main() {
testStruct()
testMap()
testSlice()
unmarshalStruct()
unmarshalMap()
unmarshalSlice()
}
func unmarshalStruct() {
var monster Monster
str := "{\"Name\":\"牛牛\",\"age\":330,\"Score\":92}"
err := json.Unmarshal([]byte(str), &monster)
if err != nil {
fmt.Printf("unmarshal err=%v", err)
}
fmt.Printf("反序列化后:%v\n", monster)
}
func unmarshalMap() {
var a map[string]interface{}
str := "{\"age\":300,\"name\":\"白骨精\",\"score\":95.5}"
err := json.Unmarshal([]byte(str), &a)
if err != nil {
fmt.Printf("unmarshal err=%v", err)
}
fmt.Printf("反序列化后:%v", a)
}
func unmarshalSlice() {
var a []map[string]interface{}
str := "[{\"age\":\"320\",\"name\":\"狮子精\",\"score\":92.5},{\"age\":\"560\",\"name\":\"大象精\",\"score\":90}]"
err := json.Unmarshal([]byte(str), &a)
if err != nil {
fmt.Printf("unmarshal err=%v", err)
}
fmt.Printf("反序列化后:%v", a)
}
- 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