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)
}
相关推荐
2501_915909064 小时前
如何保护 iOS IPA 文件中资源与文件的安全,图片、JSON重命名
android·ios·小程序·uni-app·json·iphone·webview
组合缺一6 小时前
Json Dom 怎么玩转?
java·json·dom·snack4
wtsolutions7 小时前
MCP Server Integration - JSON to Excel for AI and Automation
json·excel
\xin7 小时前
Fastjson 1.2.45仅JSON接口反序列化漏洞
安全·web安全·json
司机20488 小时前
将virtuoso原理图信息导出到json文件
json·github
Sylvia33.16 小时前
网球/羽毛球数据API:专业赛事数据服务的技术实现
java·前端·websocket·json
王家视频教程图书馆18 小时前
go语言 gin grom jwt 登陆token验证 增删改查 分页 完整 图书管理系统
gin
Watermelo61719 小时前
面向大模型开发:在项目中使用 TOON 的实践与流式处理
javascript·数据结构·人工智能·语言模型·自然语言处理·数据挖掘·json
时光慢煮19 小时前
基于 Flutter × OpenHarmony 开发的 JSON 解析工具实践
flutter·json
闻缺陷则喜何志丹19 小时前
【C# WPF】TextBox的数据绑定
ui·c#·wpf·mvvm·数据绑定·textbox