Go json.Unmarshal 字段大小写问题

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

Go json.Unmarshal field case

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Go语言还不熟悉。我试图获取并将JSON数据解析为结构体。我的示例数据如下:

var reducedFieldData = []byte(`[
    {"model":"Traverse","vin":"1gnkrhkd6ej111234"},
    {"model":"TL","vin":"19uua66265a041234"}
]`)

如果我定义接收数据的结构体如下:

type Vehicle struct {
    Model string
    Vin   string
}

调用Unmarshal函数可以正常工作。然而,如果我将字段名("model"和"vin")改为小写,与数据中的字段名匹配,它将返回空字符串作为值。

这是预期的行为吗?是否可以关闭这种约定?

英文:

I'm new to Go. I was trying to fetch and marshal json data to a struct. My sample data looks like this:

var reducedFieldData = []byte(`[
    {"model":"Traverse","vin":"1gnkrhkd6ej111234"}
	,{"model":"TL","vin":"19uua66265a041234"}
]`)

If I define the struct for receiving the data like this:

type Vehicle struct {
	Model string
	Vin   string
}

The call to Unmarshal works as expected. However, if I use lower case for the fields ("model" and "vin") which actually matches cases for the field names in the data it will return empty strings for the values.

Is this expected behavior? Can the convention be turned off?

答案1

得分: 4

需要导出字段(以大写字母开头声明)或反射库无法编辑它们。由于JSON(解)编组器使用反射,它无法读取或写入未导出的字段。

所以是的,这是预期的,不,你不能改变它。抱歉。

您可以为字段添加标签以更改编组器使用的名称:

Model string `json:"model"`

有关字段标签“encoding/json”支持的更多信息,请参阅文档

英文:

Fields need to be exported (declared with an uppercase first letter) or the reflection library cannot edit them. Since the JSON (un)marshaller uses reflection, it cannot read or write unexported fields.

So yes, it is expected, and no, you cannot change it. Sorry.

You can add tags to a field to change the name the marshaller uses:

Model string `json:"model"`

See the documentation for more info on the field tags "encoding/json" supports.

huangapple
  • 本文由 发表于 2017年7月26日 04:43:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/45313167.html
匿名

发表评论

匿名网友

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

确定