Go--using JSON struct in go language

Source: Internet
Author: User
Tags base64 base64 encode uppercase letter

Encode

Encodes an object into JSON data, accepts a interface{} object, and returns []byte and Error:

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

The marshal function recursively iterates through the entire object, encodes the object by member type, and the type conversion rule is as follows:

BOOL type conversion to JSON
Integer, floating-point number, and other numeric types converted to JSON numbers
String converted to JSON (with "" quotation marks)
struct is converted to JSON object and then recursively packaged according to the type of each member
Array or slice converted to JSON
[]byte will first Base64 encode and then convert to a JSON string
The Object,key map converted to JSON must be a string
interface{} converted according to the actual type inside
Nil converted to JSON null
Channel,func and other types will return Unsupportedtypeerror

  1. Type Colorgroup struct {
  2. ID int
  3. Name string
  4. Colors []string
  5. }
  6. Group: = colorgroup{
  7. Id:1,
  8. Name: "Reds",
  9. Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
  10. }
  11. B, err: = json. Marshal (Group)
  12. If err! = Nil {
  13. Fmt. Println ("Error:", err)
  14. }
  15. Os. Stdout.write (b)
  16. Output:
  17. {"ID": 1, "Name": "Reds", "Colors": ["Crimson", "Red", "Ruby", "Maroon"]}

Decode

Decoding the JSON data

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

Type conversion rules are similar to the above rules


  1. var jsonblob = []byte (' [
  2. {"Name": "Platypus", "Order": "Monotremata"},
  3. {"Name": "Quoll", "Order": "Dasyuromorphia"}
  4. ]`)
  5. Type Animal struct {
  6. Name string
  7. Order string
  8. }
  9. var animals []animal
  10. ERR: = json. Unmarshal (Jsonblob, &animals)
  11. If err! = Nil {
  12. Fmt. Println ("Error:", err)
  13. }
  14. Fmt. Printf ("%+v", Animals)
  15. Output:
  16. [{Name:platypus order:monotremata} {name:quoll Order:dasyuromorphia}]

Structural body

The struct must be a member of the beginning of the uppercase letter to be processed by the JSON, and the members beginning with the lowercase letter will not be affected.

When Mashal, the member variable name of the struct will be packaged directly as a key of the JSON object, and will automatically match the corresponding variable names for assignment, which is not case sensitive.

Unmarshal, if there are extra fields in the JSON, it will be discarded directly, if the JSON is missing a field, then directly ignore the variable assignment in the struct, without error.

  1. Type Message struct {
  2. Name string
  3. Body string
  4. Time Int64
  5. Inner string
  6. }
  7. var m = message{
  8. Name: "Alice",
  9. Body: "Hello",
  10. time:1294706395881547000,
  11. Inner: "OK",
  12. }
  13. B: = []byte (' {' "NAmE": "Bob", "Food": "Pickle", "inner": "Changed"} ')
  14. ERR: = json. Unmarshal (b, &m)
  15. If err! = Nil {
  16. Fmt. Printf (Err. Error ())
  17. Return
  18. }
  19. Fmt. Printf ("%v", m)
  20. Output:
  21. {Bob Hello 1294706395881547000 OK}

Structtag

If you want to manually configure the corresponding relationship between the members of the struct and the JSON field, you can label the members when you define the structure body:

With Omitempty, if the field is nil or 0 values (the number 0, the string "", the empty array [], and so on), then the wrapped JSON result will not have this fields.

  1. Type Message struct {
  2. Name string ' JSON: ' msg_name '//Msg_name for JSON
  3. Body string ' JSON: ' body,omitempty '//Ignore field if empty
  4. Time Int64 ' JSON: '-' '//ignore fields directly
  5. }
  6. var m = message{
  7. Name: "Alice",
  8. Body: "",
  9. time:1294706395881547000,
  10. }
  11. Data, err: = json. Marshal (M)
  12. If err! = Nil {
  13. Fmt. Printf (Err. Error ())
  14. Return
  15. }
  16. Fmt. Println (String (data))
  17. Output:
  18. {"Msg_name": "Alice"}
More flexibility in using JSON

Use JSON. Rawmessage

Json. Rawmessage is actually a redefinition of the []byte type. You can make a forced type conversion.

There is now a scenario in which the format of one of the fields in the struct is unknown:

< param name= "wmode" value= "Transparent" >
    1. Type Command struct {
    2. ID int
    3. CMD string
    4. Args *json. Rawmessage
    5. }

Use JSON. Rawmessage, the args field is not parsed at Unmarshal, and the byte data is assigned to args directly. We can first unpack the first layer of JSON data, and then determine the specific type of args for the second Unmarshal, based on the value of CMD.

It is important to note that you must use the pointer type *json. Rawmessage, otherwise the args are considered to be []byte types, which are packaged as Base64 encoded strings when packaged.

Use interface{}

interface{} When the type is Unmarshal, JSON is automatically converted to the corresponding data type:

Boolean conversion of JSON to BOOL
The value of JSON is converted to float64
JSON strings converted to string
The JSON array is converted to []interface{}
JSON object converted to map[string]interface{}
JSON null converted to nil

There are two needs to be aware of. One is that all JSON values are automatically converted to the Float64 type, which needs to be manually converted to the desired int,int64 type. The second is that the JSON object is automatically converted to the map[string]interface{} type, accessed directly using the field name of the JSON object as key. If you do not know the format of the JSON data, you can use interface{}.

Custom Types

You can implement the following interfaces if you want to define your own package unpacking methods:

    1. Type Marshaler Interface {
    2. Marshaljson () ([]byte, error)
    3. }
    4. Type Unmarshaler Interface {
    5. Unmarshaljson ([]byte) error
    6. }

Objects that implement this interface need to package and package their own data. If the interface is implemented, JSON will call a custom method when unpacking the package, and no more processing of the object.

Go--using JSON struct in go language

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.