问题描述
我想绑定一个像这样的对象的json数组:
[
{
"id": "someid"
},{
"id": "anotherid"
}
]
这是我的模型
type DeleteByID struct {
ID string `json:"id" binding:"required"`
}
我使用 gin 来处理对象
var stock []DeleteByID
if err := ctx.ShouldBindJSON(&stock); err != nil {
return err
}
问题是它不绑定/检查我的对象。
解决方法
您可以像这样使用 json.Unmarshal()
来实现这一点:
var stock []DeleteByID
body,err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithError(400,err)
return
}
err = json.Unmarshal(body,&stock)
if err != nil {
c.AbortWithError(400,err)
return
}
c.String(200,fmt.Sprintf("%#v",stock))