【问题标题】:Why Golang cannot generate json from struct with front lowercase character?为什么 Golang 不能从带有前小写字符的结构生成 json?
【发布时间】:2014-03-16 12:39:10
【问题描述】:

我正在尝试从我创建的结构中打印 json 结果,如下所示:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}

打印出来

m:= &Machine{ m_ip:"test", m_type:"test", m_serial:"test" }
m_json:= json.Marshal(m)
fmt.Println(m_json)

但是,返回的结果只是 {}

其次,我尝试将单词的第一个字母更改为大写如下:

type Machine struct{
  MachIp string
  MachType string
  MachSerial string
}

它有效!为什么前面带小写字母的单词不管用?

【问题讨论】:

标签: go goroutine


【解决方案1】:

Go 用例来确定特定标识符在包的上下文中是公共的还是私有的。在您的第一个示例中,json.Marshal 看不到这些字段,因为它不是包含您的代码的包的一部分。当您将字段更改为大写时,它们会变为公开,因此可以导出。

如果您需要在 JSON 输出中使用小写标识符,您可以使用所需的标识符标记字段。例如:

type Machine struct{
    MachIp     string `json:"m_ip"`
    MachType   string `json:"m_type"`
    MachSerial string `json:"m_serial"`
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 2020-07-10
    • 2021-11-11
    • 2022-11-14
    • 2021-08-31
    • 2016-12-08
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多