如何在golang中将http响应正文解析为json格式? [英] How to parse http response body to json format in golang?

查看:97
本文介绍了如何在golang中将http响应正文解析为json格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个回应机构.正文的格式如下:

I get an response body. the format of the body is as below:

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

我想将正文解析为json结构,我的代码如下:

I want to parse the body to json struct, my code is as below:

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

总是出现错误:无法将数组解组为xxx类型的Go值,有人可以提供帮助吗?

It always give an error:cannot unmarshal array into Go value of type xxx, can someone give a help?

推荐答案

在搜索入门级Go问题时,我实际上偶然发现了这个问题,所以我想留言:

I actually stumbled upon this question while googling entry-level Go questions, so I figured I'd leave a message:

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,无需对其内容进行任何事先了解就对其进行解码,然后将其打印到stdout.请记住,最好实际分配某种类型.

This downloads an example JSON url, decodes it without any prior knowledge of its contents and prints to stdout. Keep in mind that it would be better to actually assign a type of some kind.

这篇关于如何在golang中将http响应正文解析为json格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆