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)
}
相关推荐
njsgcs2 天前
json转excel python pd
python·json·excel·pd
代码搬运媛2 天前
【架构相关】tsconfig.json 与 tsconfig.node.json、tsconfig.app.json 的关系和作用
node.js·json
aerror3 天前
json转excel xlsx文件
开发语言·python·json
掉鱼的猫4 天前
全球首个支持 IETF JSONPath (RFC 9535) 标准的 Java 框架,Snack4-Jsonpath v4.0.0 发布
java·json
吹个口哨写代码4 天前
处理文本编辑器存的json格式报错问题,对编辑器存的字段进行转换处理,再通过json返回
java·编辑器·json
APIshop4 天前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
千码君20165 天前
Go语言:记录一下Go语言系统学习的第一天
java·开发语言·学习·golang·gin·并发编程·编译语言
得物技术5 天前
从 JSON 字符串到 Java 对象:Fastjson 1.2.83 全程解析|得物技术
java·后端·json
GISBox5 天前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
C嘎嘎嵌入式开发5 天前
(20)100天python从入门到拿捏《JSON 数据解析》
开发语言·python·json