• 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代替。

      

     

      

      

      

  • 相关阅读:
    linux软件安装与卸载
    杂项搜集整理
    AS3的反编译
    linux驱动杂项
    Android 匿名共享内存C++接口分析
    S3C2440 之SPI
    二叉树
    ajax简介
    SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is enabled
    让 collabtive-11 支持中文
  • 原文地址:https://www.cnblogs.com/phpper/p/16157358.html
Copyright © 2020-2023  润新知