ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] > [github](https://github.com/mailru/easyjson) ## 概述 * 在不使用反射的情况下将JSON结构封送/从JSON封送 * 在性能测试中,easyjson的性能要比标准encoding/json包好4-5倍,而其他JSON编码包要好2-3倍 * easyjson为我们实现了json.Marshaller接口,因此将调用这些函数,而不是基于反射的默认函数 ![](https://img.kancloud.cn/06/c4/06c4c77ba6b1fcb3beb60e9ba660764c_925x253.png) ## 安装 ``` go get -u github.com/mailru/easyjson/... ``` 简单demo ``` //easyjson:json type User struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"` } easyjson -all [/path/][file.go] ``` ## 接口 ``` Usage of easyjson: -all generate marshaler/unmarshalers for all structs in a file -build_tags string build tags to add to generated file -leave_temps do not delete temporary files -no_std_marshalers don't generate MarshalJSON/UnmarshalJSON funcs -noformat do not run 'gofmt -w' on output file -omit_empty omit empty fields by default -output_filename string specify the filename of the output -pkg process the whole package instead of just the given file -snake_case use snake_case names instead of CamelCase by default -lower_camel_case use lowerCamelCase instead of CamelCase by default -stubs only generate stubs for marshaler/unmarshaler funcs -disallow_unknown_fields return error if some unknown field in json appeared ``` ### simple demo ``` ├── demo │ └── a.go ├── demo333.iml ├── go.mod └── main.go ``` ``` //a.go //easyjson:json type User struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"` } //执行 easyjson -all ./demo //main.go u := demo.User{Name: "yan1", Age: 12} user1, err := u.MarshalJSON() if err != nil { println("error") } println("user = ", string(user1)) //json:=`{"id":11,"name":"yan","age":11}` user2 := demo.User{} user2.UnmarshalJSON([]byte(user1)) fmt.Printf("%+v\n", user2) // {Id:0 Name:yan1 Age:12} //执行 go run main.go ```