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
}

逆シリアル化コードは同じままです。シリアル化コードは 1 行で変更されます。

var userBytes, _ = json.Marshal(user.UserInfo)

play.golang.com

于 2013-09-12T06:23:36.703 に答える
1

タグではそれができません。json.Marshaler除外したいフィールドを除外するように実装する必要があります。

MarshalJSONマーシャリング全体を書き直したくないので、構造体のを書くのは少し難しいでしょう。type Password stringJSON 表現として空のものを返すために、マーシャラーを作成し、そのマーシャラーを作成することをお勧めします。

于 2013-09-12T06:24:58.723 に答える