繁体   English   中英

如何在golang中将http响应体解析为json格式?

[英]How to parse http response body to json format in golang?

我得到一个响应体。 正文的格式如下:

  [
    {
       "id":1,
       "name":"111" 
    },
    {
       "id":2,
       "name":"222" 
    }
  ]

我想将正文解析为 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)
  }

它总是给出一个错误:cannot unmarshal array into Go value of xxx,有人可以帮忙吗?

实际上,我在搜索入门级 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)
}

这会下载一个示例 JSON url,在不了解其内容的情况下对其进行解码并打印到标准输出。 请记住,最好实际分配某种类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM