为什么 Golang 无法从首字母小写的结构体生成 JSON?

huangapple go评论86阅读模式
英文:

Why Golang cannot generate json from struct with front lowercase character?

问题

我正在尝试从我创建的结构体中打印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
}

这样就可以正常工作了!为什么以小写字母开头的单词不起作用呢?

英文:

I am trying to print json result from struct I created as following:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}

and print out

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

However, result returned just {}

Secondly,I tried to changed the first letter of words to Uppercase as follow:

type Machine struct{
  MachIp string
  MachType string
  MachSerial string
}

and it works! Why doesn't the word with lowercase character at the front work, anyway?

答案1

得分: 81

Go语言使用大小写来确定特定标识符在包的上下文中是公开的还是私有的。在你的第一个例子中,这些字段对于json.Marshal来说是不可见的,因为它不是包含你代码的包的一部分。当你将这些字段改为大写时,它们变成了公开的,因此可以被导出。

然而,如果你需要在JSON输出中使用小写标识符,你可以使用所需的标识符对字段进行标记。例如:

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

Go uses case to determine whether a particular identifier is public or private within the context of your package. In your first example, the fields are not visible to json.Marshal because it is not part of the package containing your code. When you changed the fields to be upper case, they became public so could be exported.

If you need to use lower case identifiers in your JSON output though, you can tag the fields with the desired identifiers. For example:

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

huangapple
  • 本文由 发表于 2014年2月17日 17:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/21825322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定