dongtanliefang8765 2017-11-13 02:16
浏览 67
已采纳

Golang在编组而不是编组时会忽略Json字段

Assume I have a password field in a User struct.

type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

  • 写回答

3条回答 默认 最新

  • dsa80833 2017-11-13 08:21
    关注

    One common approach is to use a temporary type or variable, with same structure, but different json tags or even different structure:

    type User struct {
        UserName string `json:"username"`
        Password string `json:"password"`
    }
    
    func (usr User) MarshalJSON() ([]byte, error) {
        var tmp struct {
            UserName string `json:"username"`
        }
        tmp.UserName = usr.UserName
        return json.Marshal(&tmp)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器