This is a creation in Article, where the information may have evolved or changed.
In JSON encoding, the most troublesome is the JSON array, the following document I encountered in the JSON coding problems and the source of the solution:
If you want to package this format:
{"Key": 222, "msg": {"ed": "AAA", "GF": "23.45", "RS": "All"}, "Status": 1}
The code is as follows:
Package Mainimport ("Encoding/json", "FMT") func main () {t: = Make (map[string]interface{}) t["ed"] = "AAA" t["rs"] = "All" t[" GF "] =" 23.45 "Res: = Make (map[string]interface{}) res[" status "] = 1res[" key "] = 222res[" msg "] = tbody, err: = json. Marshal (RES) if err! = Nil {fmt. PRINTLN (ERR) return} else {fmt. Println (String (Body))}}
If you want to package the following format:
{"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "rs": "%"}], "Status": 1}
The code is as follows:
Package Mainimport ("Encoding/json", "FMT") func main () {var rbody []map[string]interface{}t: = Make (Map[string]interface {}) t["ed"] = "AAA" t["rs"] = "" t["GF"] = "23.45" rbody = append (rbody, t) Res: = Make (map[string]interface{}) res["status"] = 1res["key"] = 222res["msg"] = rbodybody, err: = json. Marshal (RES) if err! = Nil {fmt. PRINTLN (ERR) return} else {fmt. Println (String (Body))}}
In parsing the JSON structure, the most troublesome is parsing the JSON array, such as parsing:
{"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "rs": "%"}], "Status": 1}
The code is as follows:
Package Mainimport ("Encoding/json" "FMT") type TT struct {Key intmsg []msgstatus int}type msg struct {Ed Stringrs STRINGGF String}func Main () {Tests: = Tt{}body: = ' {"Key": 222, "MSG": [{"ed": "AAA", "GF": "23.45", "RS": "+"}], "Status": 1} ' Jsonerr: = json. Unmarshal ([]byte (body), &tests)/*[]byte () is a string that can be cast into the city byte*/if Jsonerr! = nil {fmt. Println (Jsonerr) return}fmt. PRINTLN (Tests. Key) fmt. PRINTLN (Tests. Msg[0]. ED)}