我得到一个响应主体。正文的格式如下:
[
{
"id":1,
"name":"111"
},
{
"id":2,
"name":"222"
}
]
Run Code Online (Sandbox Code Playgroud)
我想将正文解析为 json 结构,我的代码如下:
type Info struct {
Id uint32 `json:id`
Name string `json:name`
}
type Response struct {
infos []Info
}
v := &Response{}
data, err := ioutil.ReadAll(response.Body)
if err := json.Unmarshal(data, v); err != nil {
log.Fatalf("Parse response failed, reason: %v \n", err)
}
Run Code Online (Sandbox Code Playgroud)
它总是报错:cannot unmarshal array into Go value of type xxx,有人可以帮忙吗?
d33*_*tah 15
实际上,我在谷歌搜索入门级 Go 问题时偶然发现了这个问题,所以我想我应该留言:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
url := "https://skishore.github.com/inkstone/all.json"
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var j interface{}
err = json.NewDecoder(resp.Body).Decode(&j)
if err != nil {
panic(err)
}
fmt.Printf("%s", j)
}
Run Code Online (Sandbox Code Playgroud)
这将下载一个示例 JSON url,在事先不了解其内容的情况下对其进行解码并打印到 stdout。请记住,最好实际分配某种类型。
| 归档时间: |
|
| 查看次数: |
22417 次 |
| 最近记录: |