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)

1
2
3
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

1
2
# for Go < 1.17
go get -u github.com/mailru/easyjson/...
1
2
# 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

1
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下执行:

1
easyjson -all student.go

运行完后,该文件夹中有一个student_easyjson.go,该文件中就是easyjson帮我们生成的MarshalJSON和UnmarshalJSON方法. 

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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代替。

  

 

  

  

  

posted @   周伯通之草堂  阅读(971)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2019-04-17 PHP 中move_uploaded_file 上传中文文件名失败
2017-04-17 php面试题汇总四(基础篇附答案)
2017-04-17 php面试题汇总三(基础篇附答案)
2017-04-17 php面试题汇总二(基础篇附答案)
2017-04-17 php面试题汇总一(基础篇附答案)
2017-04-17 Git的commit your changes or stash them before you can merge
点击右上角即可分享
微信分享提示