编组而不是编组时如何忽略JSON字段 [英] How to ignore JSON fields when marshalling not unmarshalling

查看:107
本文介绍了编组而不是编组时如何忽略JSON字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在User结构中有一个密码字段.

Assume I have a password field in a User struct.

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

我的客户通过一起发布用户名和密码来注册他们的用户.因此,如果我将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/

我可以在结构中添加一个额外的字段,但我首先需要知道是否可以使用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.

推荐答案

一种常见的方法是使用结构相同,但json标记不同甚至结构不同的临时类型或变量:

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

这篇关于编组而不是编组时如何忽略JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆