dongtaotao19830418 2016-07-21 03:13
浏览 11
已采纳

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

I was really hoping the below code would work, but it doesn't so currently I have to manually set values from one struct to another.

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))
}

Output...I don't want to show the secret field

{"name":"Jim","password":"some_secret_password","locale":"en"}
  • 写回答

1条回答 默认 最新

  • dt1888 2016-07-21 08:39
    关注

    Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

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

    The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

    // 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"`
    

    So your code should be:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真