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)
}
相关推荐
亚林瓜子8 小时前
Jackson注解屏蔽某些字段读取权限
spring·json·jackson
不惑_14 小时前
最佳实践 · 如何高效索引MySQL JSON字段
java·mysql·json
天上掉下来个程小白1 天前
请求响应-05.请求-日期参数&JSON参数
spring boot·json
敲代码不忘补水1 天前
Python Pickle 与 JSON 序列化详解:存储、反序列化与对比
开发语言·python·json
jackletter2 天前
c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])
c#·json·序列化
A 八方2 天前
Python JSON
开发语言·python·json
小故渊2 天前
JSON对象
运维·服务器·json
SelectDB技术团队2 天前
查询性能提升 10 倍、存储空间节省 65%,Apache Doris 半结构化数据分析方案及典型场景
数据结构·数据仓库·elasticsearch·log4j·json
D11_3 天前
pandas:读取各类文件方法以及爬虫时json数据保存
爬虫·python·数据分析·json·pandas
深夜吞食4 天前
项目实现:云备份③(配置文件加载模块、数据管理模块的实现)
linux·c语言·c++·json