我有一个如下所示的 JSON 对象:
{"API version":"1.2.3"}
我想使用 json.Unmarshal()
将其转换为对象go 中的函数。根据this blog post :
How does
Unmarshal
identify the fields in which to store the decoded data? For a given JSON key"Foo"
,Unmarshal
will look through the destination struct's fields to find (in order of preference):
- An exported field with a tag of
"Foo"
(see the Go spec for more on struct tags),- An exported field named
"Foo"
, or- An exported field named
"FOO"
or"FoO"
or some other case-insensitive match of"Foo"
.
unmarshal documentation 证实了这一点.
由于“API版本”中有一个空格,这不是一个有效的go标识符,所以我在该字段上使用了一个标签:
type ApiVersion struct {
Api_version string "API version"
}
我尝试像这样解码它:
func GetVersion() (ver ApiVersion, err error) {
// Snip code that gets the JSON
log.Println("Json:",string(data))
err = json.Unmarshal(data,&ver)
log.Println("Unmarshalled:",ver);
}
输出为:
2014/01/06 16:47:38 Json: {"API version":"1.2.3"}
2014/01/06 16:47:38 Unmarshalled: {}
如您所见,JSON 没有被编码到 ver
中。我错过了什么?
最佳答案
encoding/json
模块要求结构体标签具有命名空间。所以你想要类似的东西:
type ApiVersion struct {
Api_version string `json:"API version"`
}
这样做是为了使 json
结构标记可以与其他库(例如 XML 编码器)中的标记共存。
关于json.Unmarshal 似乎不关注结构标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943963/