使用 Go 进行 JSON 解码失败

标签 json go decoding

我在解码 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 解码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53835866/

相关文章:

data-structures - 链表实现的指针问题

PHP URL 编码/解码表单字段的 %u2019 中的漂亮引号

go - 在不影响当前进程的情况下,使用 rlimit 限制子进程的内存使用

json - 在使用 circe 解码 JSON 对象时捕获未使用的字段

java - Php 编码 - Java 解码(URL 部分)

ios - 将json作为字符串保存到核心数据并使用字符串创建对象数组

jquery - 使用 JSON 将对象数组从 jsp 传递到 java servlet

ios - 在 xcode 中访问 JSON 对象

带有 json 的 android ListView - 如何使用 AsyncTask?

interface - 用接口(interface)来干燥我的 Go 函数