请教一个 gin 绑定 json 时忽略为空字段的问题

2020-10-14 21:16:47 +08:00
 LotteWong

以下字段 name, description, maxBandwidthIn 和 maxBandwidthOut 都不是必选的,我希望前端没有传过来的字段在结构体中也可以被忽略。以下是我写的有问题的代码,不知道各位大佬平时都是怎么处理这样的需求呢🤔还望大家多多指教(((蟹蟹~


type UpdateModel struct {
	Name       		string `json:"name" binding:"omitempty"`
	Description     string `json:"description" binding:"omitempty"`
	MaxBandwidthIn  int    `json:"maxBandwidthIn" binding:"omitempty"`
	MaxBandwidthOut int    `json:"maxBandwidthOut" binding:"omitempty"`
}


func UpdateItem(context *gin.Context) {
	var req UpdateModel // 初始化结构体,所有字段赋默认值,binding:"omitempty"不起作用 
    
    if err = context.BindJSON(&req); err != nil {
		context.JSON( http.StatusBadRequest, err.Error())
		return
	}
    
    ...
}

3090 次点击
所在节点    Go 编程语言
6 条回复
mason961125
2020-10-14 21:20:10 +08:00
tiedan
2020-10-14 22:30:09 +08:00
字段用指针,判断指针是不是 nil
wleven
2020-10-15 09:27:26 +08:00
`json:"maxBandwidthOut,omitempty"
LotteWong
2020-10-15 09:45:02 +08:00
@mason961125
@tiedan
非常感谢~
LotteWong
2020-10-15 09:45:19 +08:00
@wleven 这个试过了也不起作用( sad.jpg
wleven
2020-10-15 10:47:31 +08:00
如果用 gorm 的话入库可以忽略空值

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/715001

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX