json - 使用 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
推荐阅读
- c# - DataGrid 作为自定义 UserControl
- javascript - CRUD从vuejs vuex中的外部组件添加对象
- ssis - Google.Cloud.Storage.V1 Nuget 包在 SSIS 脚本任务中自动删除
- python - python中内置函数的子函数/类操作
- python - 不平衡分类的权重
- javascript - JS函数不改变HTML文本的颜色如果重复
- html - 在引导程序中将 div 放在另一个 div 之上
- python - python中列表上的组合
- swagger - 在 OpenApi 3 中添加身份验证路由以生成 JWT
- c# - C#如何从基类中的派生类中获取特定类型的所有字段?