英文:
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,
- 如果你需要将“first”作为一个独立的类型:
type first []one
- 如果你不介意将“first”作为一个独立的类型,可以按照上面 @Mellow Marmot 的建议简化为:
var some []one
英文:
@rickydj,
- If you need to have "first" as a separate type:
type first []one
- If you do not care about having "first" as a separate type, just cut down to
var some []one
as @Mellow Marmot suggested above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论