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