为什么Golang不能从前面小写字符的结构生成json? [英] Why Golang cannot generate json from struct with front lowercase character?

查看:190
本文介绍了为什么Golang不能从前面小写字符的结构生成json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类型机器结构{
m_ip字符串
m_type字符串
m_serial字符串
}

并打印出

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

然而,返回的结果只是{/ b>

其次,我尝试将第一个单词改为大写,如下所示:

 类型机器结构{
MachIp字符串
MachType字符串
MachSerial字符串
}

它起作用!为什么不在前面的小写字母的单词,反正?

解决方案

Go使用大小写来判断一个特定的标识符在你的软件包的上下文中是公共的或私有的。在第一个示例中,这些字段对 json.Marshal 不可见,因为它不是包含代码的包的一部分。当您将字段更改为大写字母时,它们将变为公共,因此可以导出。



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

 类型机器结构{
MachIp字符串`json:m_ip`
MachType字符串`json:m_type`
MachSerial string`json:m_serial`
}


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?

解决方案

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

这篇关于为什么Golang不能从前面小写字符的结构生成json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆