介绍
json反序列化是指将json字符串反序列化成对应的数据类型(比如结构体、map、切片)的操作
1.反序列换结构体
package main import ( "encoding/json" "fmt" ) //定义一个结构体 type Monster struct { Name string Age int Birthday string Sal float64 Skill string } //将json字符串反序列化成struct func unmarshalStruct() { str := "{"Name":"牛魔王","Age":500,"Birthday":"2021-11-11","Sal":80000,"Skill":"牛魔拳"}" //定义一个Monster结构体的实例 var monster Monster err := json.Unmarshal([]byte(str), &monster) if err != nil { fmt.Printf("unmarshal err=%v", err) } fmt.Printf("反序列化后 monster=%v", monster) } func main() { //演示结构体反序列化 unmarshalStruct() }
2.反序列化Map
package main import ( "encoding/json" "fmt" ) //将json反序列化成map func unmarshalMap() { str := "{"address":"洪崖洞","age":30,"name":"红孩儿"}" //定义一个map var a map[string]interface{} //反序列化 //注意:反序列化map,不需要make,因为make操作被封装到Unmarshal函数 err := json.Unmarshal([]byte(str), &a) if err != nil { fmt.Printf("unmarshal err=%vn", err) } fmt.Printf("反序列化后 a=%vn", a) } func main() { unmarshalMap() }
3.反序列化slice
package main import ( "encoding/json" "fmt" ) //将json反序列化成切片 func unmarshalSlice() { str := "[{"address":"beijiang","age":7,"name":"jack"},{"address":["shanghai","xiaweiyi"],"age":20,"name":"tom"}]" //定义一个slice var slice []map[string]interface{} //反序列化,不需要make,因为make操作被封装到Unmarshal函数 err := json.Unmarshal([]byte(str), &slice) if err != nil { fmt.Printf("unmarshal err=%vn", err) } fmt.Printf("反序列化后 slice=%vn", slice) } func main() { unmarshalSlice() }