Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gin bindJson array of objects

Tags:

go

go-gin

I would like to bind a json array of objects like this one :

[
    {
        "id": "someid"
    },
    {
        "id": "anotherid"
    }
]

Here my model

type DeleteByID struct {
    ID string `json:"id" binding:"required"`
}

I use gin to handle the object

var stock []DeleteByID
if err := ctx.ShouldBindJSON(&stock); err != nil {
 return err
}

The problem is that it does not bind/check my object.

like image 551
Yok0 Avatar asked Mar 30 '26 00:03

Yok0


1 Answers

You can achieve this by using json.Unmarshal() like this:

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))
like image 51
meshkati Avatar answered Apr 02 '26 04:04

meshkati