为什么 Golang 的 json.Unmarshal 在处理 “e” 和 “E” 属性时不起作用?

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

Why is Golang json.Unmarshall not working with "e" and "E" properties?

问题

假设我们想要解析JSON字符串 {"e": "foo", "E": 1}

使用类型 messageUppercaseE 进行解析可以正常工作。但是,当使用类型 message 时,会返回错误信息 json: cannot unmarshal number into Go struct field message.e of type string

  1. 如果只有 "e" 结构标签存在,为什么我们无法解析JSON?
  2. 如何解析JSON?(我知道可以使用 Jeffail/gabs 来实现,但我想坚持使用基于类型的方法。)
type message struct {
	EventType string `json:"e"`
}

type messageUppercaseE struct {
	EventType  string `json:"e"`
	UppercaseE uint64 `json:"E"`
}

请在 https://play.golang.org/p/T6KMJRLy7TN 上尝试一下。

英文:

Suppose we want to unmarshal the JSON string {"e": "foo", "E": 1}.

Unmarshalling using the type messageUppercaseE works like expected. When using the type message though, the error json: cannot unmarshal number into Go struct field message.e of type string is returned.

  1. Why are we not able to unmarshal the JSON, if only the "e" struct tag is present?
  2. How would I be able to unmarshal the JSON? (I know that I am able to do this via Jeffail/gabs, but would like to stick to the type based approach.)
type message struct {
	EventType string `json:"e"`
}

type messageUppercaseE struct {
	EventType  string `json:"e"`
	UppercaseE uint64 `json:"E"`
}

Try it yourself at https://play.golang.org/p/T6KMJRLy7TN

答案1

得分: 5

引用unmarshal的文档:

> 为了将JSON解组为结构体,Unmarshal将传入的对象键与Marshal使用的键进行匹配(可以是结构字段名称或其标签),优先选择精确匹配,但也接受不区分大小写的匹配。

在这种情况下,正是不区分大小写的匹配导致了问题。

英文:

Quoting the docs for unmarshal:

> To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match.

In this case, it is the case-insensitive match that causes the trouble.

huangapple
  • 本文由 发表于 2021年9月11日 00:02:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69134989.html
匿名

发表评论

匿名网友

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

确定