最近在项目中遇到了easyjson包的使用,于是自己系统的学习了以下。
1、easyjson的安装:
go get -u github.com/mailru/easyjson/
go install github.com/mailru/easyjson/easyjsonorgo
build -o easyjson github.com/mailru/easyjson/easyjson
2、验证是否安装成功,在终端输入easyjson
[@ledudeMacBook-Pro:goTest (master)]$ easyjson
Usage of easyjson:
-all
generate marshaler/unmarshalers for all structs in a file
-build_tags string
build tags to add to generated file
-disallow_unknown_fields
return error if any unknown field in json appeared
-leave_temps
do not delete temporary files
-lower_camel_case
use lowerCamelCase names instead of CamelCase by default
-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
-stubs
only generate stubs for marshaler/unmarshaler funcs
3、使用:在需要序列化的结构体上面加上注解://easyjson:json
在终端输入命令:easyjson -all 含有序列化结构体的文件名
//easyjson:json
type User struct {
Id int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func Test(){
u := User{Name:"yan1",Age:12}
user1,err :=u.MarshalJSON()
if err != nil {
println("error")
}
println("after marshal user = ",user1)
//json:=`{"id":11,"name":"yan","age":11}`
user2 := User{}
user2.UnmarshalJSON([]byte(user1))
println("name = ",user2.Name)
}
在终端输入命令:easyjson -all user.go(文件路径),后会在user.go下生成一个user_easyjson.go文件。
在这个user_easyjson.go文件中会自动生成对应的序列化和反序列化方法:
// MarshalJSON supports json.Marshaler interface
func (v User) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjson9e1087fdEncodeGoTestEasyJson(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
// MarshalEasyJSON supports easyjson.Marshaler interface
func (v User) MarshalEasyJSON(w *jwriter.Writer) {
easyjson9e1087fdEncodeGoTestEasyJson(w, v)
}
// UnmarshalJSON supports json.Unmarshaler interface
func (v *User) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjson9e1087fdDecodeGoTestEasyJson(&r, v)
return r.Error()
}
// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *User) UnmarshalEasyJSON(l *jlexer.Lexer) {
easyjson9e1087fdDecodeGoTestEasyJson(l, v)
}