我有以下结构,我想从 JSON 中读取并写入 JSON。我想读取 PasswordHash 属性(反序列化它)但在写入对象时跳过(序列化它)。是否可以标记对象,使其在反序列化时被读取但在序列化时被忽略?在json:"-"似乎跳过这两个操作领域。type User struct { // Must be unique UserName string // The set of projects to which this user has access Projects []string // A hash of the password for this user // Tagged to make it not serialize in responses PasswordHash string `json:"-"` // Is the user an admin IsAdmin bool}我的反序列化代码如下:var user Usercontent = //Some Contenterr := json.Unmarshal(content, &user)序列化代码是:var userBytes, _ = json.Marshal(user)var respBuffer bytes.Bufferjson.Indent(&respBuffer, userBytes, "", " ")respBuffer.WriteTo(request.ResponseWriter)
2 回答
万千封印
TA贡献1891条经验 获得超3个赞
我认为你不能用 json 标签做到这一点,但看起来输入用户和输出用户实际上是不同的语义对象。最好在代码中将它们分开。这样很容易实现你想要的:
type UserInfo struct {
// Must be unique
UserName string
// The set of projects to which this user has access
Projects []string
// Is the user an admin
IsAdmin bool
}
type User struct {
UserInfo
// A hash of the password for this user
PasswordHash string
}
您的反序列化代码保持不变。序列化代码在一行中更改:
var userBytes, _ = json.Marshal(user.UserInfo)
- 2 回答
- 0 关注
- 172 浏览
添加回答
举报
0/150
提交
取消