下面由golang教程栏目给大家详解Json序列化在golang中的应用 ,希望对需要的朋友有所帮助!
type Hero struct { Name string Age int Birthday string Sal float64 Skill string}
hero := Hero{ Name: "小王", Age: 20, Birthday: "2021-02-23", Sal: 88.02, Skill: "技能",}jsonStu, err := json.Marshalif err != nil { fmt.Println("生成json字}fmt.Println(string(jsonStu))
str := "{\"Name\":\"张三丰\",\"Age\":98,\"Birthday\":\"2001-09-21\",\"Sal\":3800.85,\"Skill\":\"武当剑法\"}" var hero Hero err := json.Unmarshal([]byte(str), &hero) if err != nil { fmt.Printf("unmarshal err=%v\n", err) }
俩种方式,一种直接反序列化成 结构体数组,另一种反序列化为 slice,内容为map[string]interface{}
结构体数组
str := `[{"Name":"张三丰","Age":98,"Birthday":"2001-09-21","Sal":3800.85,"Skill":"武当剑法"},{"Name":"张无忌","Age":28,"Birthday":"2004-09-21","Sal":300.85,"Skill":"乾坤大挪移"}]` var hero []Hero err := json.Unmarshal([]byte(str), &hero) if err != nil { fmt.Printf("unmarshal err=%v\n", err) } fmt.Printf("反序列化后 hero=%v", hero)
slice
str := `[{"Name":"张三丰","Age":98,"Birthday":"2001-09-21","Sal":3800.85,"Skill":"武当剑法"},{"Name":"张无忌","Age":28,"Birthday":"2004-09-21","Sal":300.85,"Skill":"乾坤大挪移"}]` //定义一个slice var slice []map[string]interface{} //注意:反序列化map,不需要make,因为make操作被封装到Unmarshal函数 err := json.Unmarshal([]byte(str), &slice) if err != nil { fmt.Printf("unmarshal err=%v\n", err) } fmt.Printf("反序列化后 slice=%v\n", slice)
以上就是详解Json序列化在golang中的应用的详细内容,更多请关注其它相关文章!