英文:
Cannot unmarshall a json array in golang
问题
我目前有一个看起来像这样的 JSON 数组:
[
{
"name": "foo",
"age": "12",
"id": "12"
},
{
"name": "foo",
"age": "12",
"id": "12"
}
]
现在上面是一个 JSON 数组。我为上述对象创建的结构如下:
type CustType struct {
Name string `json:"name"`
Age string `json:"age"`
}
然而,为了从数组解组到结构体,我创建了以下结构体:
type CustTypes struct {
MyTypes []CustType
}
然后我这样做:
e := CustTypes{}
json.Unmarshal([]byte(str), &e)
然而,我没有得到任何解组的结果。你有什么想法,我可能做错了什么?我在结构体中跳过了 id
字段,但我相信这不会影响结果。
英文:
I currently have a json array that looks like this
[
{
"name": "foo",
"age": "12",
"id": "12"
},
{
"name": "foo",
"age": "12",
"id": "12"
}
]
Now the above is a json array. The object I have for the above is
type CustType struct {
Name string `json:"name"`
Age string `json:"age"`
}
However to unmarshal from an array to struct I created this
type CustTypes struct {
MyTypes []CustType
}
then I am doing this
e := CustTypes{}
json.Unmarshal([]byte(str), &e)
However I am not getting anything unmarshalled. Any idea what I might be doing wrong ? I did skip the field id
in the struct but I believe that does not affect the result.
答案1
得分: 1
始终检查你的错误:
err = json:无法将数组解组为类型为main.CustTypes的Go值
问题在于你试图将一个数组解组为一个对象。直接解组为MyTypes
。
err := json.Unmarshal([]byte(str), &e.MyTypes)
当使用fmt.Printf
时,我得到以下结果:
e = {MyTypes:[{Name:foo Age:12} {Name:foo Age:12}]}
英文:
Always check your errors:
err = json: cannot unmarshal array into Go value of type main.CustTypes
The problem is that you're trying to unmarshal an array into an object. Unmarshal directly into MyTypes
.
err := json.Unmarshal([]byte(str), &e.MyTypes)
I get the following when using fmt.Printf
:
e = {MyTypes:[{Name:foo Age:12} {Name:foo Age:12}]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论