Go?easyjson使用及反射原理
如果使用go語言自帶的json庫,使用的是反射,而go語言中反射性能較低。easyjson就是一個比較好的替代方案。
esayjson安裝(https://gitcode.net/mirrors/mailru/easyjson?utm_source=csdn_github_accelerator)
go get -u github.com/mailru/easyjson go install github.com/mailru/easyjson/easyjsonorgo go build -o easyjson github.com/mailru/easyjson/easyjson(這里默認(rèn)在當(dāng)前目錄生成easyjson二進制可執(zhí)行文件)
安裝easyjson
# for Go < 1.17 go get -u github.com/mailru/easyjson/... # for Go >= 1.17 go get github.com/mailru/easyjson && go install github.com/mailru/easyjson/...@latest
說下我的環(huán)境:win10,go1.18,如下圖
安裝完畢后,GOPATH里bin下就有easyjson.exe。
使用go env 查看如我的gopath為:C:\Users\77293\go
使用easyjson
go mod init demo
比如我的當(dāng)前工作目錄demo下初始化mod,創(chuàng)建一個文件夾model,在model下新建student.go文件:
定義結(jié)構(gòu)體:
記得在需要使用easyjson的結(jié)構(gòu)體上加上//model:json 標(biāo)注。 此處model是我的包路徑名即為model,代碼如下:
package model import "time" //model:json type School struct { Name string `json:"name"` Addr string `json:"addr"` } type Student struct { Id int `json:"id"` Name string `json:"s_name"` School School `json:"s_chool"` Birthday time.Time `json:"birthday"`
可以進入結(jié)構(gòu)體包model下執(zhí)行:
easyjson -all student.go
運行完后,該文件夾中有一個student_easyjson.go,該文件中就是easyjson幫我們生成的MarshalJSON和UnmarshalJSON方法.
使用示例
package main import ( "demo/model" "fmt" "time" ) func main() { s := model.Student{ Id: 11, Name: "qq", School: model.School{ Name: "CUMT", Addr: "xz", }, Birthday: time.Now(), } bt, err := s.MarshalJSON() // MarshalJSON fmt.Println(string(bt), err) json := `{"id":1,"s_name":"克萊爾","s_chool":{"name":"中南","addr":"wuhan"},"birthday":"2003-08-04T20:58:07.9894603+08:00"}` str := model.Student{} str.UnmarshalJSON([]byte(json)) // UnmarshalJSON fmt.Println(str) }
運行結(jié)果:
{"id":11,"s_name":"qq","s_chool":{"name":"CUMT","addr":"xz"},"birthday":"2022-04-17T20:48:07.9274949+08:00"} <nil>
{1 克萊爾 {中南 wuhan} 2003-08-04 20:58:07.9894603 +0800 CST
小結(jié):go自帶JSON庫使用的反射原理,性能相對較差,可以使用easyjson代替。
到此這篇關(guān)于Go easyjson使用技巧的文章就介紹到這了,更多相關(guān)Go easyjson使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang?IOT中的數(shù)據(jù)序列化與解析過程
這篇文章主要介紹了Golang?IOT中的數(shù)據(jù)序列化與解析,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05淺析Golang開發(fā)中g(shù)oroutine的正確使用姿勢
很多初級的Gopher在學(xué)習(xí)了goroutine之后,在項目中其實使用率不高,所以這篇文章小編主要來帶大家深入了解一下goroutine的常見使用方法,希望對大家有所幫助2024-03-03優(yōu)雅使用GoFrame共享變量Context示例詳解
這篇文章主要為大家介紹了優(yōu)雅使用GoFrame共享變量Context示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06MacOS中 VSCode 安裝 GO 插件失敗問題的快速解決方法
這篇文章主要介紹了MacOS中 VSCode 安裝 GO 插件失敗問題的快速解決方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05