Golang的JSON解码在数组上失败。

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

Golang json decoding fails on Array

问题

我有一个对象,如下所示:

a = [{
    "name": "rdj",
    "place": "meh",
    "meh": ["bow", "blah"]
}]

我定义了一个结构体,如下所示:

type first struct {
    A []one
}

type one struct {
    Place string `json:"place"`
    Name  string `json:"name"`
}

当我在代码中使用相同的结构体时:

func main() {
    res, _ := http.Get("http://127.0.0.1:8080/sample/")
    defer res.Body.Close()
    var some first
    rd := json.NewDecoder(res.Body)
    err := rd.Decode(&some)
    errorme(err)
    fmt.Printf("%+v\n", some)
}

我得到以下错误:

panic: json: cannot unmarshal array into Go value of type main.first

我的理解是:

type first 定义了一个数组,数组中包含了 type one 定义的数据结构。

英文:

I have an object like:

   a = [{
        "name": "rdj",
        "place": "meh",
        "meh" : ["bow", "blah"]
    }]

I defined a struct like:

type first struct {
	A []one
}

type one struct {
	Place string `json: "place"`
	Name string `json: "name"`
}

when I use the same in code like:

func main() {
	res, _ := http.Get("http://127.0.0.1:8080/sample/")
	defer res.Body.Close()
	var some first
	rd := json.NewDecoder(res.Body)
	err := rd.Decode(&some)
	errorme(err)
	fmt.Printf("%+v\n", some)
}

I get the below error:

panic: json: cannot unmarshal array into Go value of type main.first

My understanding is:

type first defines the array and within that array is data structure defined in type one.

答案1

得分: 2

JSON是一个对象数组。使用以下类型:

type one struct {   // 使用结构体表示JSON对象
  Place string `json:"place"`
  Name string `json:"name"`
}

...

var some []one   // 使用切片表示JSON数组
rd := json.NewDecoder(res.Body)
err := rd.Decode(&some)

问题中的类型与此JSON结构匹配:

{
  "A": [
    {
      "name": "rdj",
      "place": "meh",
      "meh": ["bow", "blah"]
    }
  ]
}
英文:

The JSON is an array of objects. Use these types:

type one struct {   // Use struct for JSON object
  Place string `json: "place"`
  Name string `json: "name"`
}

...

var some []one   // Use slice for JSON array
rd := json.NewDecoder(res.Body)
err := rd.Decode(&some)

The the types in the question match this JSON structure:

{"A": [{
    "name": "rdj",
    "place": "meh",
    "meh" : ["bow", "blah"]
}]}

答案2

得分: 1

@rickydj,

  1. 如果你需要将“first”作为一个独立的类型:
type first []one
  1. 如果你不介意将“first”作为一个独立的类型,可以按照上面 @Mellow Marmot 的建议简化为:
var some []one
英文:

@rickydj,

  1. If you need to have "first" as a separate type:
type first []one
  1. If you do not care about having "first" as a separate type, just cut down to
var some []one

as @Mellow Marmot suggested above.

huangapple
  • 本文由 发表于 2016年11月30日 02:51:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/40873562.html
匿名

发表评论

匿名网友

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

确定