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条)

报告相同问题?

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数