如何在go中标记一个结构,以便它从JSON读取值但不写入它们?

Usm*_*ail 1 json go

我有以下结构,我想从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
}
Run Code Online (Sandbox Code Playgroud)

我的反序列化代码如下:

var user User
content = //Some Content
err := json.Unmarshal(content, &user)
Run Code Online (Sandbox Code Playgroud)

和序列化代码是:

var userBytes, _ = json.Marshal(user)
var respBuffer bytes.Buffer
json.Indent(&respBuffer, userBytes, "", "   ")
respBuffer.WriteTo(request.ResponseWriter)
Run Code Online (Sandbox Code Playgroud)

Klu*_*uyg 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
}
Run Code Online (Sandbox Code Playgroud)

您的反序列化代码保持不变.序列化代码在一行中更改:

var userBytes, _ = json.Marshal(user.UserInfo)
Run Code Online (Sandbox Code Playgroud)

play.golang.com