客户端参数 { id:20 sign:90cb901a631a3260c59d90724e893da9 timestamp:1681459261 role_id:3 } 注意:不是表单key value格式,是整个json数据 后端处理 type ArticleCommentLikeForm struct { ID int32 form:"id" alias:"ID" binding:"required" Timestamp int32 form:"timestamp" alias:"文章ID" binding:"required" Sign string form:"sign" alias:"文章ID" binding:"required" RoleId int32 form:"role_id" alias:"角色ID" binding:"required" } var param ArticleCommentLikeForm err := ctx.ShouldBind(&param); 获取不到RoleId的值

Comment From: baytan0720

既然是json数据,就不应该使用tag 'form'了,换成'json'

Comment From: baytan0720

It's JSON data, use 'json' tag instead of 'form'

Comment From: zhaohaihang

just as : type ArticleCommentLikeForm struct { ID int32 alias:"ID" binding:"required" json:"id" Timestamp int32 alias:"文章ID" binding:"required" json:"timestamp" Sign string alias:"文章ID" binding:"required" json:"sign" RoleId int32 alias:"角色ID" binding:"required" json:"role_id" }

Comment From: ChZhg123

既然是json数据,就不应该使用tag 'form'了,换成'json'

嗯嗯,json确实可以,但是如果参数不带下划线的话,form也是可以接受数据的,这是什么原因?

Comment From: ChZhg123

just as : type ArticleCommentLikeForm struct { ID int32 alias:"ID" binding:"required" json:"id" Timestamp int32 alias:"文章ID" binding:"required" json:"timestamp" Sign string alias:"文章ID" binding:"required" json:"sign" RoleId int32 alias:"角色ID" binding:"required" json:"role_id" }

嗯嗯,json确实可以,但是如果参数不带下划线的话,form也是可以接受数据的,这是什么原因

Comment From: baytan0720

我猜测是你的请求头中包含"Content-Type":"application/json",gin将其通过ShouldBindJSON()解析到结构体中,但是没有检查到字段有json tag,则默认key为字段名的小写形式,也就是form tag其实并不起作用 I guess that your request header contains "Content-Type": "application/json". Gin parses it into the structure through ShouldBindJSON(), but there is not json tag in the field, the default key is the lowercase form of the field name, that is, the form tag doesn't work.