Go language exercise: building JSON and parsing JSON instances

Source: Internet
Author: User
Tags ming uppercase letter

This article describes how to use the Go language library to convert objects to JSON format, transfer them in the channel, and convert the information in JSON format back to the object.

1, the Go Language JSON library

The go language comes with a JSON conversion library of Encoding/json

  1.1) The method (function) in which the object is converted to JSON is JSON. Marshal (), whose function is prototyped as follows

    Func Marshal (v interface{}) ([]byte, error)

That is, the function receives any type of data vand converts it to a byte array type, and the return value is the JSON data we want and an error code. When the conversion succeeds, the error code is nil

In the process of converting an object to JSON, the following rules are followed:

• Boolean is still Boolean after conversion to JSON, such as true-true

• Floating-point and integer conversions are normal numbers in JSON, such as 1.23-1.23

• Strings will be converted to strings that are output as Unicode character sets in UTF-8 encoding, special characters such as < will be escaped to \u003c

arrays and slices are converted to arrays in JSON, [the]byte class is converted to Base64 encoded string, slice's 0 value is converted to null

• The structure is transformed into a JSON object, and only the exportable fields that begin with uppercase letters in the struct are converted to output, and these exportable fields are indexed as strings of JSON objects

• When converting a data structure of a map type, the data must be of type map[string]t (T can be any data type supported by the Encoding/json package)

  1.2) Convert the JSON back to the object's method (function) to JSON. Unmarshal (), whose function is prototyped as follows

    Func unmarshal (data [] byte, v interface{}) error

This function parses the incoming data as a JSON, and the parsed information is stored in the parameter v . This parameter v is also a parameter of any type (but must be a pointer to a type), because when we parse the JSON with this function, the function does not know the specific type of the incoming parameter, so it needs to receive all the types.

So, when parsing, what happens if the JSON and object structures do not correspond to each other, this requires parsing the function json. Unmarshal () follow these rules

JSON. The Unmarshal () function finds the fields in the target structure in the order of a contract, and if one is found , a match occurs. So what did we find out? The following rules apply to " found ": Suppose a JSON object has an index named "foo", and the value corresponding to "foo" is populated to the target field of the target struct,json. Unmarshal () will follow the following order to find matches

      § a field containing the Foo label

      § a field named Foo

      § a field named Foo or foo, or except the first letter other letters are case-insensitive. These fields must be in the type declaration that begin with an uppercase letter and can be exported.

    Note : If the field in JSON does not exist in the go target type,json. The Unmarshal () function discards the field during decoding.

• When the structure of JSON is unknown, the following rules are followed:

      § The Boolean value in JSON will be converted to the bool type in Go

      § values will be converted to the float64 type in Go

      § string conversion or String type

      § JSON array is converted to []interface{} type

      § JSON object is converted to map[string]interface{} type

      § null value is converted to nil

    Note : In the standard library Encoding/json package of Go, allow values of type map[string]interface{} and []interface{} to hold JSON objects or arrays of unknown structure, respectively

2. code example

Suppose we have the following class (struct) student and one of its instance objects St:

Type Studentstruct{Namestring AgeintGuakeBOOLClasses []stringPrice float32}st:= &Student {"Xiao Ming",     -,    true,    []string{"Math","中文版","Chinese"},     9.99,}

Now we need to convert an object of this class into a JSON format and transfer it to a friend far away, so we can do this:

B, err: = json. Marshal (ST)

This translates well. Isn't it simple! Converting back is easier, for example we have a new student object called STB, then we can convert it back:

STB: = &= json. Unmarshal ([]byte(strdata), &STB)

This is converted back, is not very simple!

The following is the complete code and the result of the operation:

$ cat Gojson.go

1 Package Main2 3 Import (4     "FMT"5     "Encoding/json"6 )7 8Type Studentstruct {9NamestringTenAgeint OneGuakeBOOL AClasses []string - Price float32 - } the  -Func (S *Student) Showstu () { -Fmt. Println ("Show Student:") -Fmt. Println ("\tname\t:", S.name) +Fmt. Println ("\tage\t:", S.age) -Fmt. Println ("\tguake\t:", S.guake) +Fmt. Println ("\tprice\t:", S.Price) AFmt. Printf ("\tclasses\t:") at      for_, A: =Range S.classes { -Fmt. Printf ("%s", a) -     } -Fmt. Println ("") - } -  in Func Main () { -ST: = &Student { to         "Xiao Ming", +          -, -         true, the[]string{"Math","中文版","Chinese"}, *         9.99, $     }Panax NotoginsengFmt. Println ("before JSON encoding:") - St. Showstu () the  +B, err: =JSON. Marshal (ST) A     ifErr! =Nil { theFmt. Println ("encoding Faild") +}Else { -Fmt. Println ("encoded data:") $ FMT. Println (b) $Fmt. Println (string(b)) -     } -CH: = Make (chanstring,1) theGo func (c chanstringStrstring){ -C <-StrWuyi} (CH,string(b)) theStrdata: = <-CH -Fmt. Println ("--------------------------------") WuSTB: = &student{} - STB. Showstu () AboutErr = json. Unmarshal ([]byte(Strdata), &STB) $     ifErr! =Nil { -Fmt. Println ("Unmarshal faild") -}Else { -Fmt. Println ("Unmarshal Success") A STB. Showstu () +     } the}

Operation Result:

$ go Run gojson.go before JSON encoding:show Student:Name:Xiao Ming Age: -Guake:truePrice :9.99Classes:math 中文版 Chinese encoded data: [123  the  +  the 109 101  the  -  the  the  the  the 111  +  the  the  the 103  the  -  the  $ 103 101  the  -  the  Wu  -  the  in 117  the 107 101  the  -  the  the 117 101  -  the  the 108  the  the  the 101  the  the  -  the  the  the  the  the 104  the  -  the  the  the 103 108  the  the 104  the  -  the  the 104  the  the 101  the 101  the  the  -  the  the  the  the  About 101  the  -  $  $  $  $  the]{"Name":"Xiao Ming"," Age": -,"Guake":true,"Classes":["Math","中文版","Chinese"]," Price":9.99}--------------------------------Show Student:Name:Age:0Guake:falsePrice :0Classes:unmarshal successshow Student:Name:Xiao Ming Age: -Guake:truePrice :9.99Classes:math 中文版 Chinese

Storm

Mail: [Email protected]

Go language exercise: building JSON and parsing JSON instances

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.