Golang JSON encoding decoding

Source: Internet
Author: User

Golang "Encoding/json" package implements encoding and decoding of JSON objects

One, the code

Interface {}) ([]byte, error)

The Marshal function uses the following type-based default encoding format:

The Boolean type is encoded as a JSON Boolean type.

Values for floating-point, Integer, and number types are encoded as JSON numeric types.

The string is encoded as a JSON string. The angle brackets "<" and ">" are escaped as "\u003c" and "\u003e" to avoid some browser bar JSON output incorrectly interpreted as HTML. For the same reason, "&" is escaped as "\u0026".

The values for array and slice types are encoded as JSON arrays, but []byte encoded as base64 encoded strings and nil slices are encoded as null.

The value of the struct is encoded as a JSON object. Each export field becomes a member of the object

Example:

1 Package Main2 3 Import (4     "FMT"5     "Encoding/json"6 )7 Func Main () {8Type Userstruct{9NamestringTenAgeint One     } AUser: =user{ -Name:"Tom", -Age:3, the     } -B, err: =JSON. Marshal (user) -     ifErr! =Nil { -Fmt. Println ("json Marshal fail:", Err) +     } -Fmt. Println (string(b)) +}

Output:

{"Name":"Tom","Age":  3}

1 non-exportable fields are not encoded

Example:

struct {        string             int} User: = user{Name:         " Tom " , age        :3,    }    B, _:= json. Marshal (user)    FMT. Println (string(b))

Output:

{"Name":"Tom"}

2 The encoded JSON object can be changed through the structure tag

Example:

 type User struct  {Name  string  ' Json:"  name  Span style= "COLOR: #800000" > "  ' age  int ' Json: " ageeeeeeeeeeeeeeeeee   " "} User:  = user{ Name:   " tom  "  , Age:  3  ,} B, _:  = JSON. Marshal (user) fmt. Println ( string  (b)) 

Output:

{"name":"Tom","ageeeeeeeeeeeeeeeeee ":3}

3 Complex structure Code:

The pointer is encoded to the value it points to

Slice encoding Array

The value of the struct is encoded as a JSON object

Example:

    //Complex structure Coding//basic type pointers, struct pointers, slices, slice pointers,Type Contactstruct{AddrstringPhonestring} type Userstruct{Namestring Age*intC1*Contact C2 []contact C3 []*Contact } Age:= -C1:= contact{"Beijing","12345"} CARR:= [...] contact{contact{"Beijing","11111"},contact{"Shenzhen","22222"},contact{"Shanghai","33333"}} C2:= carr[:2] C3:= Make ([]*contact,0) C3= Append (C3, &carr[0]) C3= Append (C3, &carr[1]) User:=user{Name:"Tom", Age:&Age , C1:&C1, C2:C2, C3:C3,} fmt. Printf ("struct:%v\n", user) B, _:=JSON. Marshal (user) fmt. Println ("JSON:",string(b))

Output:

struct: {Tom0xc04204a1c8 0xc042044580[{Beijing11111} {Shenzhen22222}] [0xc042086000 0xc042086020]}json: {"Name":"Tom"," Age": -,"C1":{"Addr":"Beijing","Phone":"12345"},"C2":[{"Addr":"Beijing","Phone":"11111"},{"Addr":"Shenzhen","Phone":"22222"}],"C3":[{"Addr":"Beijing","Phone":"11111"},{"Addr":"Shenzhen","Phone":"22222"}]}

Second, decoding

Func unmarshal (data []byteinterface{}) Error

Example

//JSON decoding testType Contactstruct{AddrstringPhonestring} type Userstruct{Namestring Age*intC1*Contact C2 []contact C3 []*Contact } User:=user{} J:= `{                "Name":"Tom",                " Age": -,                "C1": {                    "Addr":"Beijing",                    "Phone":"12345"                },                "C2": [{                    "Addr":"Beijing",                    "Phone":"11111"                }, {                    "Addr":"Shenzhen",                    "Phone":"22222"                }],                "C3": [{                    "Addr":"Beijing",                    "Phone":"11111"                }, {                    "Addr":"Shenzhen",                    "Phone":"22222"}]} ' err:= json. Unmarshal ([]byte(j), &user)ifErr! =Nil {fmt. Println ("JSON unmarshal fail!")} FMT. Printf ("%v\n", user) fmt. Println (*user. Age) Fmt. Println (*user. C1) fmt. Println (*user. c3[0])

Output

0xc04204a3a8 0xc0420447a0 11111 22222}] [0xc0420448600xc042044880]}12345   11111}

Reference: Go language standard library document Chinese version

Golang JSON encoding decoding

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.