1

我有以下结构,我想从 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 User
content = //Some Content
err := json.Unmarshal(content, &user)

序列化代码是:

var userBytes, _ = json.Marshal(user)
var respBuffer bytes.Buffer
json.Indent(&respBuffer, userBytes, "", "   ")
respBuffer.WriteTo(request.ResponseWriter)
4

2 回答 2

5

我认为你不能用 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)

play.golang.com

于 2013-09-12T06:23:36.703 回答
1

你不能用标签做到这一点。您必须实施json.Marshaler以排除要排除的字段。

为结构编写 a 会有点棘手MarshalJSON,因为您不想重写整个编组。我建议你有一个type Password string, 并编写 marshaler 来返回一些空的东西作为它的 JSON 表示。

于 2013-09-12T06:24:58.723 回答