登录
首页 >  Golang >  Go问答

使用 Go 进行 JSON 解码失败

来源:stackoverflow

时间:2024-04-02 22:18:25 221浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《使用 Go 进行 JSON 解码失败》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我在解码 http 响应正文时遇到一些问题。我使用 insomnia 得到的响应如下所示:

[
  {
    "name": "monitoring",
    "instances": [
      {
        "host": "ite00716.local",
        "id": "2058b934-720f-47c5-a1da-3d1535423b83",
        "port": 8080
      }
    ]
  },
  {
    "name": "app1",
    "instances": [
      {
        "host": "172.20.10.2",
        "id": "bc9a5859-8dda-418a-a323-11f67fbe1a71",
        "port": 8081
      }
    ]
  }
]

当我使用以下 go 代码时,我解码到的结构是空的。我不知道为什么。请帮助我!

type Service struct {
    Name      string     `json:"name"`
    Instances []Instance `json:"instances"`
}

type Instance struct {
    Host string `json:"host"`
    Id   string `json:"id"`
    Port int    `json:"port"`
}

func main() {
    resp, err := http.Get("http://localhost:8080/services")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    var s Service

    json.NewDecoder(resp.Body).Decode(&s)

    fmt.Println(s)
}

解决方案


您的 json 响应是服务数组

var s []Service

好了,本文到此结束,带大家了解了《使用 Go 进行 JSON 解码失败》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>