2.9 JSON讀寫1:JSON序列化
阿新 • • 發佈:2018-12-09
概述 序列化:將Go資料轉化為json字串
定義結構體
type Person struct {
Name string
Age int
Sex bool
Hobbies []string
}
定義資料
var (
zhangqd, mutz Person
ps []Person
mMap, yMap map[string]interface{}
mSlice []map[string]interface{}
)
初始化資料
func init() {
//初始化結構體資料
zhangqd = Person{"張全蛋", 20, true, []string{"質檢", "維護流水線", "打飯"}}
mutz = Person{"穆鐵花", 23, false, []string{"搞破壞", "維護流水線", "打人"}}
ps = make([]Person, 0)
ps = append(ps, zhangqd, mutz)
//初始化map資料
mMap = make(map[string]interface{})
mMap["name"] = "張全蛋"
mMap["age"] = 20
mMap["sex" ] = true
mMap["hobbies"] = []string{"質檢", "維護流水線", "打飯"}
yMap = make(map[string]interface{})
yMap["name"] = "穆鐵柱"
yMap["age"] = 23
yMap["sex"] = false
yMap["hobbies"] = []string{"破壞", "維護流水線", "打人"}
//初始化切片資料
mSlice = make([]map[string]interface{}, 0)
mSlice = append (mSlice, mMap, yMap)
}
序列化結構體
func main11() {
//bytes, err := json.Marshal(zhangqd)
bytes, err := json.Marshal(ps)
if err != nil {
fmt.Println("序列化失敗,err=", err)
} else {
jsonStr := string(bytes)
fmt.Println("序列化結果:", jsonStr)
}
}
序列化map
func main12() {
bytes, err := json.Marshal(mMap)
if err != nil {
fmt.Println("序列化失敗,err=", err)
} else {
jsonStr := string(bytes)
fmt.Println("序列化結果:", jsonStr)
}
}
序列化切片
func main13() {
bytes, err := json.Marshal(mSlice)
if err != nil {
fmt.Println("序列化失敗,err=", err)
} else {
jsonStr := string(bytes)
fmt.Println("序列化結果:", jsonStr)
}
}