gin框架 POST 请求参数绑定 JSON数据ShouldBind 使用注意事项 - 结构体必须定义json标签

gin框架中的请求数据绑定ShouldBind可将前端发送的数据直接绑定到自定义结构体, 但是在POST发送JSON 数据时 需要注意 因为gin框架在底层绑定数据时使用了json对参数进行了反序列化, 所以我们在自定义的结构体中,如果前端发送的JSON中的字段和自定义结构体的字段的命名方式不一致时必须要增加json标签。 否则无法获取数据

后端自定义的结构体:

Go 复制代码
type NoticeApiCreateReq struct {
	NoticeID          int32    // 公告ID
	NoticeTitle       string   // 公告标题
}

前端的POST请求JSON

bash 复制代码
{
    "notice_id": 1,
    "notice_title": "Hello world"
}

这时如果后端的结构体中不增加JSON标签, 则在使用ShouldBind绑定数据时是无法获取到数据的,因为你的字段命名方式不一致。

解决方式有2个

1 是将前端的发送字段命名和后端结构体中的定义保存一致(不推荐)

2.是在自定义结构体中增加json标签,将json标签的名称和前端发送的JSON名称保存一致即可.

重新修改后的结构体定义

Go 复制代码
type NoticeApiCreateReq struct {
	NoticeID  int32     `form:"notice_id" json:"notice_id" `        
	NoticeTitle  string    `json:"notice_title"`     

}

注意上面的结构体字段tag中的 form:"notice_id" 这个form标签对应POST JSON数据而言是可选的,这个form标签是给表单方式请求时用的, 如果前端是以JSON方式发送的数据,则只需要定义 json标签即可。

gin框架使用ShouldBind方法绑定POST JSON数据示例

Go 复制代码
// 新增页面保存
func (a *noticeApi) Post(c *ginx.XContext) {

	var req = &dto.NoticeApiCreateReq{}
	//获取参数
	if err := c.ShouldBind(req); err != nil {
		a.Err(c, err.Error())
		return
	}
    // ......你的业务处理逻辑

}

总结:gin框架中的ShouldBInd方法绑定前端发送的数据会自动根据请求数据类型来选择合适的数据绑定方法,对于JSON数据的绑定你也可以使用 ShouldBindJSON方法,最后的效果是一样的。 同时要注意gin框架底层对应json数据的绑定,他实际上使用的是json包中的函数 func Unmarshal(data []byte, v any) error { 来完成的, 所以,如果你的命名不统一,则结构体字段必须要指定json标签。

json.Unmarshal函数参考

Go 复制代码
// To unmarshal a JSON object into a map, Unmarshal first establishes a map to
// use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
// reuses the existing map, keeping existing entries. Unmarshal then stores
// key-value pairs from the JSON object into the map. The map's key type must
// either be any string type, an integer, implement [json.Unmarshaler], or
// implement [encoding.TextUnmarshaler].
//
// If the JSON-encoded data contain a syntax error, Unmarshal returns a [SyntaxError].
//
// If a JSON value is not appropriate for a given target type,
// or if a JSON number overflows the target type, Unmarshal
// skips that field and completes the unmarshaling as best it can.
// If no more serious errors are encountered, Unmarshal returns
// an [UnmarshalTypeError] describing the earliest such error. In any
// case, it's not guaranteed that all the remaining fields following
// the problematic one will be unmarshaled into the target object.
//
// The JSON null value unmarshals into an interface, map, pointer, or slice
// by setting that Go value to nil. Because null is often used in JSON to mean
// "not present," unmarshaling a JSON null into any other Go type has no effect
// on the value and produces no error.
//
// When unmarshaling quoted strings, invalid UTF-8 or
// invalid UTF-16 surrogate pairs are not treated as an error.
// Instead, they are replaced by the Unicode replacement
// character U+FFFD.
func Unmarshal(data []byte, v any) error {
	// Check for well-formedness.
	// Avoids filling out half a data structure
	// before discovering a JSON syntax error.
	var d decodeState
	err := checkValid(data, &d.scan)
	if err != nil {
		return err
	}

	d.init(data)
	return d.unmarshal(v)
}
相关推荐
Dxy123931021615 小时前
Python 将 JSON 字符串转换为字典
前端·python·json
草根大哥20 小时前
AI编程实践-homex物业管理平台(Go + Vue3 + MySQL 多租户落地)
mysql·golang·vue·ai编程·gin·物业管理系统·多租户
一个天蝎座 白勺 程序猿1 天前
破译JSON密码:KingbaseES全场景JSON数据处理实战指南
数据库·sql·json·kingbasees·金仓数据库
叫我龙翔1 天前
【计网】从零开始掌握序列化 --- JSON实现协议 + 设计 传输\会话\应用 三层结构
服务器·网络·c++·json
Ancelin安心1 天前
FastJson反序列化和Shiro漏洞
java·运维·开发语言·安全·web安全·json·idea
倔强的石头1061 天前
JSON 数据看得头大?这个工具转成图表后,远程同事也能一起分析
json·cpolar
CaracalTiger1 天前
如何解决Unexpected token ‘<’, “<!doctype “… is not valid JSON 报错问题
java·开发语言·jvm·spring boot·python·spring cloud·json
全栈小51 天前
【C#】合理使用DeepSeek相关AI应用为我们提供强有力的开发工具,在.net core 6.0框架下使用JsonNode动态解析json字符串,如何正确使用单问号和双问号做好空值处理
人工智能·c#·json·.netcore·deepseek
Promise微笑2 天前
语义占位与数字信任:Geo优化中Json-LD的战略重构与实操路径
重构·json
H_ZMY2 天前
从零吃透JSON:前端/后端必学的轻量级数据交换神器
前端·json·状态模式