Golang JSON encoding decoding

Source: Internet
Author: User

JSON encoding

Package Mainimport ("Encoding/json", "FMT") type person struct {name string ' JSON: ' name ' ' Age int ' json: ' Age ' '}func main () C0/>{person: = person{"Ruby", 24}b, err: = json. Marshal (&person) If Err = = Nil {fmt. Printf ("%s\n", B)} else {//error handling}}

  

Key method JSON. Marshal:

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

The result of this method is a byte array, which, if needed, can be string (XXX), such as:

Fmt. Println (string (b))

  

JSON decoding

Package Mainimport ("Encoding/json", "Strings" "FMT") type person struct {name string ' JSON: ' name ' ' Age int ' json: ' Age '} Func Main () {//JSON string to decode str: = ' {' name ': ' Ruby ', ' age ': ' + '//JSON decoder object, there is a Decode method that accepts a struct parameter decoder: = Json. Newdecoder (Strings. Newreader (str)) var person personerr: = decoder. Decode (&person) If Err = = Nil {fmt. Println (person. Name) fmt. Println (person. Age)}}

  

Writing a line is (str is a string that needs decoding, V is a struct variable, and you need to decode what struct to define the struct variable):

Json. Newdecoder (Strings. Newreader (str)). Decode (v)

  

Problems:

1. Why do I define a struct, but use JSON. Marshal method encoding returns an empty byte[]?

Possible cause: The struct uses a lowercase field name, such as

Type person struct {    name string age    int}

The field name needs to be renamed to the Hump, if the field name after the code needs to be lowercase, you can add a tag to the struct, as in the example above

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.