有没有一种很好的方法可以不在json有效负载中公开某些struct属性?

时间:2016-07-21 03:13:13

标签: go

我真的希望下面的代码可以正常工作,但它目前还不是必须手动设置从一个结构到另一个结构的值。

https://play.golang.org/p/yfcsaNJm9M

package main

import "fmt"
import "encoding/json"

type A struct {
    Name     string `json:"name"`
    Password string `json:"password"`
}

type B struct {
    A
    Password string `json:"-"`
    Locale   string `json:"locale"`
}

func main() {

    a := A{"Jim", "some_secret_password"}
    b := B{A: a, Locale: "en"}

    data, _ := json.Marshal(&b)
    fmt.Printf("%v", string(data))
}

输出......我不想显示秘密字段

{"name":"Jim","password":"some_secret_password","locale":"en"}

1 个答案:

答案 0 :(得分:1)

  

Struct值编码为JSON对象。每个导出的struct字段   成为对象的成员,除非

- the field's tag is "-", or
- the field is empty and its tag specifies the "omitempty" option.
  

空值为false,0,任何nil指针或接口值,以及   任何长度为零的数组,切片,映射或字符串。对象的默认值   key字符串是struct字段名称,但可以在struct中指定   字段的标记值。 struct字段的标记值中的“json”键是   键名,后跟可选的逗号和选项。例子:

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is     empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

所以你的代码应该是:

package main

import "fmt"
import "encoding/json"

type A struct {
    Name     string `json:"name"`
    Password string `json:"password"`
}

type B struct {
    A
    Password string `json:"password,omitempty"`
    Locale   string `json:"locale"`
}

func main() {

    a := A{"Jim", "some_secret_password"}
    b := B{A: a, Locale: "en"}

    data, _ := json.Marshal(&b)
    fmt.Printf("%v", string(data))
}

https://play.golang.org/p/HdwIssr-oC