Home > Article > Backend Development > Detailed explanation of the application of Json serialization in golang
The following is a detailed explanation of the application of Json serialization in golang from the golang tutorial column. I hope it will be helpful to friends in need!
Golang’s operation of json serialization and deserialization is really uncomfortable, so I’m used to using advanced Language features, it will be difficult to switch to these native writing methods.
Not much BB, start recording.
When writing a small demo or making a small tool without large-scale usage scenarios, it is the same whichever library is used, because Performance will not be obvious. But if it is used in actual projects and is accompanied by high concurrency, large capacity and other scenarios, I still recommend using json-iterator
.
"encoding/json" 官当自带
It is known as the fastest go json parser. It is compatible with the official writing method. I basically use this now.
github.com/json-iterator/go
Efficiency comparison
ns Nanosecond op operation
ns/op | allocation bytes | allocation times | |
---|---|---|---|
std decode | 35510 ns/op | 1960 B/op | 99 allocs/op |
easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op |
jsoniter decode | 5623 ns/ op | 160 B/op | 3 allocs/op |
std encode | 2213 ns/op | 712 B/op | 5 allocs/op |
easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op |
jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op |
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) }
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)
The above is the detailed content of Detailed explanation of the application of Json serialization in golang. For more information, please follow other related articles on the PHP Chinese website!