反序列化:是指将json字符串反序列化成原来的数据类型。
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 unmarshalStruct() { str := "{"name":"牛魔王","age":10,"birthday":"1994-09-18","sal":10000,"skill":"牛魔拳"}" var monster monster err := json.Unmarshal([]byte(str), &monster) if err != nil { fmt.Println("unmarshal error=", err) } fmt.Printf("反序列化后 monster=%v ", monster) fmt.Println(monster.Name) } func unmarshalMap() { str := "{"address":"水帘洞","age":20,"name":"孙悟空","skill":"七十二变"}" var a map[string]interface{} err := json.Unmarshal([]byte(str), &a) if err != nil { fmt.Println("unmarshal error=", err) } fmt.Printf("反序列化后 monster=%v ", a) } func unmarshalSlice() { str := "[{"address":"水帘洞","age":20,"name":"孙悟空","skill":["七十二变","如意金箍棒"]}," + "{"age":30,"name":"猪八戒"}]" var a []map[string]interface{} err := json.Unmarshal([]byte(str), &a) if err != nil { fmt.Println("unmarshal error=", err) } fmt.Printf("反序列化后 monster=%v ", a) } func main() { unmarshalStruct() unmarshalMap() unmarshalSlice() }
需要注意的是:在反序列化之后的数据类型要与json字符串相对应。