Golang High Performance JSON package: Easyjson

Source: Internet
Author: User
Tags lexer lua

Brief introduction

What is Easyjson? According to the official website, Easyjson is an efficient, fast and easy-to-use structural Structs<-->json conversion package. Easyjson is not implemented using reflection, so the performance is 4-5 times more than the other JSON packages, 2-3 times faster than the JSON package that Golang comes with. The Easyjson goal is to keep the build code simple so that it can be easily optimized or fixed.

Installation

Go get-u github.com/mailru/easyjson/go install Github.com/mailru/easyjson/easyjsonorgo build-o Easyjson github.com/ Mailru/easyjson/easyjson

Verify that the installation is successful.

$ easyjsonusage of d:\code\go\bin\easyjson.exe:  -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  -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   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

There are several options to be aware of:

-lower_camel_case: Change the struct field first letter to lowercase.  such as Name=>name.  -build_tags string: Generates the specified string to the head of the generated go file.  -no_std_marshalers: Marshaljson/unmarshaljson function is not generated for the struct. -omit_empty: Fields that are not assigned can not be generated to JSON, otherwise field is the default value for that domain type. -output_filename: Defines the generated file name. -pkg: A corresponding Easyjson configuration is generated for the '//easyjson:json ' struct specified within the package. -snke_case: Can underline the field as ' name_student ' instead of ' name_student '.

Use

Remember to add to the structure you need to use easyjson //easyjson:json . As follows:

Execute under the structure package

Easyjson-all Student.go

A new file appears in the directory at this time.

 code generated by easyjson for marshaling/unmarshaling. do not  EDIT.package easyjsonimport  (    json  "Encoding/json"      easyjson  "Github.com/mailru/easyjson"     jlexer  "github.com/mailru/ Easyjson/jlexer "    jwriter " Github.com/mailru/easyjson/jwriter ")// suppress  unused package warningvar  (    _ *json. Rawmessage    _ *jlexer. Lexer    _ *jwriter. Writer    _ easyjson. Marshaler) Func easyjsonb83d7b77decodestudygoeasyjson (in *jlexer. lexer, out *student)  {    istoplevel := in. Isstart ()     if in. IsNull ()  {        if isTopLevel {          &Nbsp;  in. Consumed ()         }        in. Skip ()         return    }     In. Delim (' {')     for !in. Isdelim ('} ')  {        key := in. Unsafestring ()         in. Wantcolon ()         if in. IsNull ()  {            in. Skip ()             in. Wantcomma ()             continue         }        switch key {         case  "id": &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;    out. Id = int (in. Int ())         case  "S_name":             out. Name = string (in. String ())         case  "S_chool":             easyjsonb83d7b77decodestudygoeasyjson1 (in, &out. School)         case  "Birthday":             if data := in. Raw ();  in. Ok ()  {                in. Adderror (out. Birthday). Unmarshaljson (data)             }         default:             in. Skiprecursive ()        }        in. Wantcomma ()     }    in. Delim ('} ')     if istoplevel {        in. Consumed ()     }}func easyjsonb83d7b77encodestudygoeasyjson (Out *jwriter. writer, in student)  {    out. Rawbyte (' {')     first := true    _ = first     if !first {        out. Rawbyte (', ')     }    first = false     Out. Rawstring ("\" id\ ":")     out. int (int (in. Id))     if !first {        out. Rawbyte (', ')     }    first = false    out. Rawstring ("\" s_name\ ":")     out. String (String (in. Name))     if !first {        out. Rawbyte (', ')     }    first = false     Out. Rawstring ("\" s_chool\ ":")     easyjsonb83d7b77encodestudygoeasyjson1 (out, in. School)     if !first {        out. Rawbyte (', ')     }    first = false     Out. Rawstring ("\" birthday\ ":")     out. Raw (in. Birthday). Marshaljson ())     out. Rawbyte ('} ')}// marshaljson supports json. marshaler interfacefunc  (v student)  marshaljson ()   ([]byte, error)  {     w := jwriter. Writer{}    easyjsonb83d7b77encodestuDygoeasyjson (&AMP;W,&NBSP;V)     return w.buffer.buildbytes (), w.Error}//  Marshaleasyjson supports easyjson. marshaler interfacefunc  (v student)  marshaleasyjson (w *jwriter. Writer)  {    easyjsonb83d7b77encodestudygoeasyjson (w, v)}// UnmarshalJSON  supports json. unmarshaler interfacefunc  (v *student)  unmarshaljson (data []byte)  error {     r := jlexer. Lexer{data: data}    easyjsonb83d7b77decodestudygoeasyjson (&AMP;R,&NBSP;V)      return r.error ()}// unmarshaleasyjson supports easyjson. unmarshaler interfacefunc  (v *student)  unmarshaleasyjson (l *jlexer. Lexer)  {    easyjsonb83d7b77decodestudygoeasyjson (l, v)}func  Easyjsonb83d7b77decodestudygoeasyjson1 (in *jlexer. Lexer, out *school) &NBsp {    istoplevel := in. Isstart ()     if in. IsNull ()  {        if isTopLevel {             in. Consumed ()         }        in. Skip ()         return    }     In. Delim (' {')     for !in. Isdelim ('} ')  {        key := in. Unsafestring ()         in. Wantcolon ()         if in. IsNull ()  {            in. Skip ()             in. Wantcomma ()             continue        }         switch key {        case  "Name":             out. Name = string (in. String ())         case  "addr":             out. Addr = string (in. String ())         default:             in. Skiprecursive ()         }         in. Wantcomma ()     }    in. Delim ('} ')     if istoplevel {        in. Consumed ()     }}func easyjsonb83d7b77encodestudygoeasyjson1 (Out&nbsP;*jwriter. Writer, in school)  {    out. Rawbyte (' {')     first := true    _ = first     if !first {        out. Rawbyte (', ')     }    first = false     Out. Rawstring ("\" name\ ":")     out. String (String (in. Name))     if !first {        out. Rawbyte (', ')     }    first = false     Out. Rawstring ("\" addr\ ":")     out. String (String (in. ADDR))     out. Rawbyte ('} ')}

Now you can write a test class.

package mainimport  (     "Studygo/easyjson"      "Time"       "FMT") Func main () {    s:=easyjson. student{        id: 11,         name: "QQ",         school:easyjson. School{            name: "CUMT",    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ADDR: "XZ",         },        birthday:time. Now (),     }    bt,err:=s.marshaljson ()     fmt. Println (String (BT), err)     json:= ' {"id": One, "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))     fmt. PRINTLN (SS)}

Operation Result:

{"id": One, "S_name": "QQ", "S_chool": {"name": "Cumt", "addr": "XZ"}, "Birthday": "2017-08-04t20:58:07.9894603+08:00"} <nil>{121 {cwwwwwwwumt xzwwwww} 2017-08-04 20:52:03.4066002 +0800 CST}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.