在Go语言中,为什么我的JSON解码在这里不起作用?

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

In Go, why is my JSON decoding not working here?

问题

我无法使标准库的encoding/json包能够解码JSON对象。以下是一个最简示例:

b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
    groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)

这段代码输出:

contents = {groups:[]}
err = nil

但我期望的输出是:

contents = {groups:[{name:foo} {name:bar}]}

我做错了什么?

英文:

I cannot get the standard library's encoding/json package to work for decoding JSON objects. Here's a minimal example:

b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
    groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)

This prints:

contents = {groups:[]}
err = nil

But I expect:

contents = {groups:[{name:foo} {name:bar}]}

What am I doing wrong?

答案1

得分: 14

字段名必须以大写字母开头:

type Group struct{ Name string }
var contents struct {
	Groups []Group
}
英文:

The field names have to start with a capital letter:

type Group struct{ Name string }
var contents struct {
	Groups []Group
}

huangapple
  • 本文由 发表于 2015年9月14日 05:54:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/32554899.html
匿名

发表评论

匿名网友

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

确定