英文:
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
。
- 如果只有
"e"
结构标签存在,为什么我们无法解析JSON? - 如何解析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.
- Why are we not able to unmarshal the JSON, if only the
"e"
struct tag is present? - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论