1 Package Main2 3 Import (4 "Encoding/json"5 "FMT"6 )7 8/*9 Ten the correspondence between the go type and the JSON type One BOOL Represents the JSON Booleans, A float64 represents the JSON numbers, - string represents the JSON strings, - The nil represents JSON null. the - three-party open Source Library: -https://github.com/bitly/go-Simplejson -*/ + - type Server struct { + ServerName String A ServerIP String at } - - type serverslice struct { - Servers []server - } - in type Server2 struct { -ServerName string ' JSON:"ServerName"` toServerIP string ' JSON:"ServerIP"` + } - the type Serverslice2 struct { *Servers []server2 ' JSON:"Servers"` $ }Panax Notoginseng - Func Main () { theFmt. Println ("********************") + Jsonunmarshal () AFmt. Println ("********************") the JsonUnmarshal2 () +Fmt. Println ("********************") - Jsonmarshal () $Fmt. Println ("********************") $ JsonMarshal2 () - } - the func Jsonunmarshal () { - var s serversliceWuyistr: = ' {"Servers": the[{"ServerName":"Shanghai_vpn","ServerIP":"127.0.0.1"}, -{"ServerName":"Beijing_vpn","ServerIP":"127.0.0.2"}]}` WuJson. Unmarshal ([]byte (str), &s) - FMT. Println (s) About } $ - func JsonUnmarshal2 () { -B: = []byte (' {"Name":"Wednesday"," Age": 6,"Parents":["Gomez","Morticia"]}`) - var f interface{} AJson. Unmarshal (b, &f) +M: =F. (map[string]interface{}) the forK, V: =Range M { -Switch VV: =v. (type) { $ Case String: theFmt. Println (k,"is string", VV) the Case int: theFmt. Println (k,"is int", VV) the Case Float64: -Fmt. Println (k,"is float64", VV) in Case []interface{}: theFmt. Println (k,"is an array:") the forI, U: =Range VV { About FMT. Println (i, u) the } the Default: theFmt. Println (k,"is of a type I don ' t konw how handle") + } - } the }Bayi the func Jsonmarshal () { the var s serverslice -S.servers = Append (S.servers, Server{servername:"Shanghai_vpn", ServerIP:"127.0.0.1"}) -S.servers = Append (S.servers, Server{servername:"Beijing_vpn", ServerIP:"127.0.0.2"}) theB, err: =JSON. Marshal (s) the ifErr! =Nil { theFmt. Println ("JSON err:", Err) the } - FMT. Println (string (b)) the } the the func JsonMarshal2 () {94 var s Serverslice2 theS.servers = Append (S.servers, Server2{servername:"Shanghai_vpn", ServerIP:"127.0.0.1"}) theS.servers = Append (S.servers, Server2{servername:"Beijing_vpn", ServerIP:"127.0.0.2"}) theB, err: =JSON. Marshal (s)98 ifErr! =Nil { AboutFmt. Println ("JSON err:", Err) - }101 FMT. Println (string (b))102}
Notes Golang processing JSON