传统方式
在使用gin框架时,每次解析复杂一点的JSON数据,都需要提前写好struct,然后用ShouldBind 方法: post的JSON数据如下:
{
"trayCode":"123",
"batCodes":[
{
"position":1,
"batCode":"test1"
},
{
"position":2,
"batCode":"test2"
}
]
}
提前写好Struct:
type Parameter struct {
TrayCode string `json:trayCode`
BatCodes []BatPositionInfo `json:batCodes`
}
type BatPositionInfo struct {
BatCode string `json:batCode`
Position int `json:position`
}
使用:
func main() {
r := gin.Default()
r.POST("/post", func(c *gin.Context) {
p := &Parameter{BatCodes: make([]BatPositionInfo, 0)}
err := c.ShouldBind(p)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(p)
}
c.JSON(200, gin.H{
"msg": "this is a post msg",
})
})
panic(r.Run(":2500"))
}
动态方式
动态的方式,不需要提前声明struct,解析的时候,将json解析为map, 然后解析map中的数据
func main() {
r.POST("/post", func(c *gin.Context) {
json := make(map[string]interface{})
err := c.BindJSON(&json)
if err != nil {
fmt.Printf("bind error:%v\n", err)
} else {
traycode := json["trayCode"]
fmt.Printf("traycode:%v\n", traycode)
obj := json["batCodes"]
batCodes := make([]BatPositionInfo, 0)
for _, val := range obj.([]interface{}) {
dic, _ := val.(map[string]interface{})
pos := BatPositionInfo{
BatCode: dic["batCode"].(string),
Position: int(dic["position"].(float64)),
}
batCodes = append(batCodes, pos)
}
fmt.Printf("batCodes:%v\n", batCodes)
}
c.JSON(200, gin.H{
"msg": "this is a post msg",
})
})
panic(r.Run(":2500"))
}
|