Gin: Cannot unmarshal into struct with c.BindJson()

Created on 13 Apr 2018  路  2Comments  路  Source: gin-gonic/gin

I currently have a request body like this:

{
    "guests": [
        {
            "firstname": "ryan",
            "lastname": "vlaming"
        }
    ],
    "roomType": "suite",
    "checkinDate": "2018-04-13T19:24:00+00:00",
    "checkoutDate": "2018-07-13T19:24:00+00:00"
}

and am trying to read it into this struct

type CreateParams struct {
    Username     string `json:"username"`
    Guests       Guests `json:"guests"`
    RoomType     string `json:"roomType"`
    CheckinDate  string `json:"checkinDate"`
    CheckoutDate string `json:"checkoutDate"`
}

type Guests struct {
    Person []struct {
        firstname string
        lastname  string
    }
}

using the following code

    r := new(params.CreateParams)
    err := context.BindJSON(r)
    if err != nil {
        context.AbortWithStatusJSON(500, apierrors.JsonBindingError)
        return
    }

But i am getting the following error: json: cannot unmarshal array into Go struct field CreateParams.guests of type params.Guests

Is there any way i could read this in using the c.BindJson function, or do i need some other function for this ? or some sort of custom solution ?

question

Most helpful comment

@konojunya Thank you so much for your quick and effective reply.
Your solution worked like a charm!

Many thanks !

All 2 comments

@fabulousduck Hi, I think you can solve your problem.

I could execute my code.
Sample using gin's BindJSON

The place you'd be mistaken is the Person struct.

First of all, I do not need to create a struct called Guests for the Guests of the CreateParams struct. So in my code we write an array of Person structCreatePaams stcurt Guest with []Person.

Next, firstname andlastname of Person struct MUST capitalize the first letter. This is because you can not export a variable unless you initialize it in the Go specification.

In my sample I will upload the json file of the request in consideration of the above two points.

If you try

curl http://localhost:8000 -d @request.json

Please let me know if the problem is not resolved.

I'm Japanese and English is not fluent, so please let me know if you do not understand the meaning.

Thanks.

@konojunya Thank you so much for your quick and effective reply.
Your solution worked like a charm!

Many thanks !

Was this page helpful?
0 / 5 - 0 ratings