Go入门笔记39-EasyJson

Ubunut20.04环境
默认go marshal,Unmarshal效率较低,可以使用EasyJson
1、命令行直接输入easyjson会提示apt安装,然后安装
2、创建一个go文件,结构体上标注
//easyjson

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

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

3、命令行执行
easyjson -all student.go // 生成easyjson_student.go,为结构体增加了MarshalJSON、UnmarshalJSON方法
4、然后就可以使用了。
使用示例

package main

import (
    "studygo/easyjson"
    "time"
    "fmt"
)

func main(){
    s:=easyjson.Student{
        Id: 11,
        Name:"qq",
        School:easyjson.School{
            Name:"CUMT",
            Addr:"xz",
        },
        Birthday:time.Now(),
    }
    bt,err:=s.MarshalJSON()  // MarshalJSON
    fmt.Println(string(bt),err)
    
    json:=`{"id":11,"s_name":"qq","s_chool":{"name":"CUMT","addr":"xz"},"birthday":"2017-08-04T20:58:07.9894603+08:00"}`
    ss:=easyjson.Student{}
    ss.UnmarshalJSON([]byte(json))  // UnmarshalJSON
    fmt.Println(ss)
}

另外测试了ffjson、json-iterator/go,感觉json-iterator效果不如easyjson.
参考:https://www.cnblogs.com/tomtellyou/p/14672479.html

posted @ 2021-09-05 21:28  zhaogaojian  阅读(318)  评论(0编辑  收藏  举报