Gin: How to bind nested json

Created on 19 Dec 2016  路  2Comments  路  Source: gin-gonic/gin

The following request works properly for the below code.
curl -X POST localhost:5005/user --data '{"name":"Neel", "email":"[email protected]" }' -H "Content-Type:application/json" -H "Authorization:Bearer <AuthToken>"

type User struct {
    Name  string `gorethink:"name" json:"name"`
    Email string `gorethink:"email" json:"email" binding:"required"`
}

func CreateUser(c *gin.Context) {
    var user User
    if c.BindJSON(&user) == nil {
        fmt.Println("Name", user.Name)
        fmt.Println("Email", user.Email)
                saveUser(user)
    }
}

How to change the above code to bind nested json. For example the request will be,
curl -X POST localhost:5005/user --data '{ "user": {"name":"Neel", "email":"[email protected]" }, "send_request":true }' -H "Content-Type:application/json" -H "Authorization:Bearer <AuthToken>"

question

Most helpful comment

Try

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

type User struct {
    Name  string `json:"name"`
    Email string `json:"email" binding:"required"`
}

type JSONRequest struct {
    Data User `json:"user" binding:"required"`
}

func main() {
    router := gin.Default()

    router.POST("/postJSON", func(c *gin.Context) {
        var json JSONRequest
        if c.BindJSON(&json) == nil {
            fmt.Println("Name", json.Data.Name)
            fmt.Println("Email", json.Data.Email)
        }
        c.String(200, fmt.Sprintf("%#v", json))
    })

    router.Run(":8080")
}

curl command:

curl -X POST -v -d "{\"user\": {\"name\": \"Bo-Yi Wu\", \"email\": \"[email protected]\"}}" localhost:8080/postJSON

All 2 comments

Try

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

type User struct {
    Name  string `json:"name"`
    Email string `json:"email" binding:"required"`
}

type JSONRequest struct {
    Data User `json:"user" binding:"required"`
}

func main() {
    router := gin.Default()

    router.POST("/postJSON", func(c *gin.Context) {
        var json JSONRequest
        if c.BindJSON(&json) == nil {
            fmt.Println("Name", json.Data.Name)
            fmt.Println("Email", json.Data.Email)
        }
        c.String(200, fmt.Sprintf("%#v", json))
    })

    router.Run(":8080")
}

curl command:

curl -X POST -v -d "{\"user\": {\"name\": \"Bo-Yi Wu\", \"email\": \"[email protected]\"}}" localhost:8080/postJSON

Thank you. it's working.

Was this page helpful?
0 / 5 - 0 ratings