json.Unmarshal 似乎不关注结构标签

标签 json go

我有一个如下所示的 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/

相关文章:

javascript - 如何在Javascript中使用where条件获取对象名称数据列表?

javascript - 如何从数组位置内的多个 json 对象访问数据

javascript - jQ : Parse localstorage & stringify values

java - 如何将 LinkedHashSet 集合添加到 JsonObjectBuilder 对象?

mongodb - 我怎样才能在 json 中响应时间毫秒为零

c++ - GO 中的闭包和局部变量

go - 如何在 golang 中从客户端接收 multipart?

python - Windows 的 Python 中包含 json 包吗?

json - 在 Revel (Golang) 中自动解析参数 JSON

go - 使用 Golang 的 Google Cloud Functions 工作流