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)
}
相关推荐
酷爱码35 分钟前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
不惑_5 小时前
用 PyQt5 打造一个可视化 JSON 数据解析工具
开发语言·qt·json
漫游者Nova8 小时前
PDF转Markdown/JSON软件MinerU最新1.3.12版整合包下载
pdf·json·markdown·mineru
snow@li1 天前
vue3+ts+vite:详细、完整的 tsconfig.json 示例 / 常见配置项及其用途
json·tsconfig.json
南郁1 天前
007-nlohmann/json 项目应用-C++开源库108杰
c++·开源·json·nlohmann·现代c++·d2school·108杰
紫乾20141 天前
idea json生成实体类
java·json·intellij-idea
fashia2 天前
Java转Go日记(六十):gin其他常用知识
开发语言·后端·golang·go·gin
我的golang之路果然有问题2 天前
ElasticSearch+Gin+Gorm简单示例
大数据·开发语言·后端·elasticsearch·搜索引擎·golang·gin
愿你天黑有灯下雨有伞2 天前
MyBatis-Plus LambdaQuery 高级用法:JSON 路径查询与条件拼接的全场景解析
mysql·json·mybatis
wtsolutions2 天前
JSON to Excel 3.0.0 版本发布 - 从Excel插件到Web应用的转变
json·excel·json-to-excel·wtsolutions