duanniwu7730 2019-02-15 05:46
浏览 53
已采纳

如何使用Gin-Gonic在Go中读取蛇案JSON请求正文

I am using gin-gonic to create my first Go rest API server.

My User struct is as follows

type User struct {
    FirstName string `json: "first_name"`
}

I have the following route defined in my code

route.POST("/test", func(c *gin.Context) {

        var user request_parameters.User
        c.BindJSON(&user)

        //some code here

        c.JSON(http.StatusOK, token)
})

My POST request body is as follows

{
    "first_name" : "James Bond"
}

The value of user.FirstName is "" in this case. But when I post my request body as

{
    "firstName" : "James Bond"
}

The value of user.FirstName is "James Bond".

How do I map the snake case variable "first_name" from the JSON request body to the corresponding variable in the struct? Am I missing something?

  • 写回答

1条回答 默认 最新

  • dongtun1872 2019-02-15 05:50
    关注

    You have a typo (a space in json: "first_name").

    It should be:

    type User struct {
        FirstName string `json:"first_name"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python使用python-pptx如何给幻灯片添加只读密码。
  • ¥15 深度神经网络传递自变量损失
  • ¥15 删除s的前驱节点,但是不知道错哪里了
  • ¥15 oracle数据库备份表如何操作
  • ¥15 软件定义网络mininet和onos控制器问题
  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错