The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
LotteWong

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

  •  
  •   LotteWong · Oct 14, 2020 · 3892 views
    This topic created in 2054 days ago, the information mentioned may be changed or developed.

    以下字段 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
    	}
        
        ...
    }
    
    
    6 replies    2020-10-15 10:47:31 +08:00
    tiedan
        2
    tiedan  
       Oct 14, 2020
    字段用指针,判断指针是不是 nil
    wleven
        3
    wleven  
       Oct 15, 2020
    `json:"maxBandwidthOut,omitempty"
    LotteWong
        4
    LotteWong  
    OP
       Oct 15, 2020
    @mason961125
    @tiedan
    非常感谢~
    LotteWong
        5
    LotteWong  
    OP
       Oct 15, 2020
    @wleven 这个试过了也不起作用( sad.jpg
    wleven
        6
    wleven  
       Oct 15, 2020
    如果用 gorm 的话入库可以忽略空值
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1014 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 18:43 · PVG 02:43 · LAX 11:43 · JFK 14:43
    ♥ Do have faith in what you're doing.