在json编码中,最麻烦的是json数组,下面记录一下我在json编码遇到的难题和解决的源代码:
如果要打包这种格式:
{"key":222,"msg":{"ed":"aaa","gf":"23.45","rs":"23"},"status":1}
代码如下:
package main import ( "encoding/json" "fmt" ) func main() { t := make(map[string]interface{}) t["ed"] = "aaa" t["rs"] = "23" t["gf"] = "23.45" res := make(map[string]interface{}) res["status"] = 1 res["key"] = 222 res["msg"] = t body, err := json.Marshal(res) if err != nil { fmt.Println(err) return } else { fmt.Println(string(body)) } }
{"key":222,"msg":[{"ed":"aaa","gf":"23.45","rs":"23"}],"status":1}
代码如下:package main import ( "encoding/json" "fmt" ) func main() { var rbody []map[string]interface{} t := make(map[string]interface{}) t["ed"] = "aaa" t["rs"] = "23" t["gf"] = "23.45" rbody = append(rbody, t) res := make(map[string]interface{}) res["status"] = 1 res["key"] = 222 res["msg"] = rbody body, err := json.Marshal(res) if err != nil { fmt.Println(err) return } else { fmt.Println(string(body)) } }
在解析json结构的时候,最麻烦是解析json数组,如解析:
{"key":222,"msg":[{"ed":"aaa","gf":"23.45","rs":"23"}],"status":1}
代码如下:package main import ( "encoding/json" "fmt" ) type tt struct { Key int Msg []msg Status int } type msg struct { Ed string Rs string Gf string } func main() { tests := tt{} body := `{"key":222,"msg":[{"ed":"aaa","gf":"23.45","rs":"23"}],"status":1}` jsonerr := json.Unmarshal([]byte(body), &tests)/*[]byte()是可以把string强制转换城byte*/ if jsonerr != nil { fmt.Println(jsonerr) return } fmt.Println(tests.Key) fmt.Println(tests.Msg[0].Ed) }
有疑问加站长微信联系(非本文作者)