一、json反序列化
package main
import (
"encoding/json"
"fmt"
)
//定义一个结构体
type Monster struct {
Name string `json:"name"`
Age int `json:"age"`
Birthday string `json:"birthday"`
Sal float64 `json:"sal"`
Skill string `json:"skill"`
}
//初始化结构体
func testStruct() {
monster := Monster{
"老王",
25,
"1995-10-10",
6000,
"打工",
}
//将monster数据序列化
bytes, err := json.Marshal(monster)
if err != nil {
fmt.Println("序列化失败",err)
}
//反序列化
err = json.Unmarshal([]byte(string(bytes)), &monster)
if err != nil {
fmt.Println("反序列化失败:",err)
}
fmt.Println("结构体:",string(bytes))
fmt.Println("结构体反序列化后:",monster)
}
//map序列化
func testMap() {
a := make(map[string]interface{})
a["name"] = "小王"
a["age"] = 12
a["address"] = "成都"
//将a序列化
data, err := json.Marshal(a)
if err != nil {
fmt.Println("序列化错误:",err)
}
//反序列化
err = json.Unmarshal([]byte(string(data)),&a)
if err != nil {
fmt.Println("反序列化失败:",err)
}
//fmt.Println("map序列化:",string(data))
fmt.Println("map反序列化后:",a)
}
//切片序列化
func testSlice() {
var slice []map[string]interface{}
b := make(map[string]interface{})
b["name"] = "老李"
b["age"] = 22
b["address"] = "江苏"
b2 := make(map[string]interface{})
b2["name"] = "老妹"
b2["age"] = 25
b2["address"] = "北京"
slice = append(slice, b)
slice = append(slice, b2)
data, err := json.Marshal(slice)
if err != nil {
fmt.Println("序列化错误:",err)
}
//反序列化
err = json.Unmarshal([]byte(string(data)),&slice)
if err != nil {
fmt.Println("反序列化失败:",err)
}
//fmt.Println("切片序列化:",string(data))
fmt.Println("切片反序列化后:",slice)
}
func main() {
testStruct()
testMap()
testSlice()
}