Go easyjson使用技巧

原文鏈接:http://www.zhoubotong.site/post/37.html

如果使用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(這裏默認在當前目錄生成easyjson二進制可執行文件)

安裝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

說下我的環境:win10,go1.18,如下圖

安裝完畢後,GOPATH裏bin下就有easyjson.exe。

使用go env 查看如我的gopath爲: C:\Users\77293\go

使用easyjson

go mod init demo

比如我的當前工作目錄demo下初始化mod,創建一個文件夾model,在model下新建student.go文件:

定義結構體:

記得在需要使用easyjson的結構體上加上//model:json 標註。 此處model是我的包路徑名即爲model,代碼如下:

package model

import "time"

//model:json
type School struct {
    Name string `json:"name"`
    Addr string `json:"addr"`
}

//model:json
type Student struct {
    Id       int       `json:"id"`
    Name     string    `json:"s_name"`
    School   School    `json:"s_chool"`
    Birthday time.Time `json:"birthday"`
}

可以進入結構體包model下執行:

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)
}

運行結果:

{"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

小結:go自帶JSON庫使用的反射原理,性能相對較差,可以使用easyjson代替。

  

 

  

  

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章