无法在 Golang 中解组 JSON 数组。

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

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}]}

huangapple
  • 本文由 发表于 2023年6月24日 06:32:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76543788.html
匿名

发表评论

匿名网友

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

确定