我在发JSON请求
req, err := http.NewRequest("GET", myPath, nil)
if err != nil {
panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var j map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&j)
if err != nil {
panic(err)
}
现在返回一个map[string]interface{}
但JSON中数据的实际形状是:
{
key1: "string"
key2: "string"
key3: [
{ key1: "string", key2: "int", key3: "Array<string>" },
{ key1: "string", key2: "int", key3: "Array<string>" },
...a lot more
]
}
我如何才能真正获得key3数据?
for key, value := range j {
if key == "key3" {
// Im stuck here,
}
}
我尝试将JSON响应解组为结构体,并将其解码为该结构体
type key3Struct struct {
key1 string
key2 string
key3 []string
}
type ResponseStruct struct {
key1 string
key2 string
key3 []key3Struct
}
// Attempt 1
j = ResponseStruct{}
json.NewDecoder(resp.Body).Decode(&j)
==> error cant convert map[string]interface{} to ResponseStruct{}
// Attempt 2
json.Unmarshal(resp.Body, &j)
==> it looks like [ {} ] no data in it...
1条答案
按热度按时间amrnrhlw1#
感谢@mkopriva的帮助,我的问题是两件事:1 -我没有为struct props提供大写字母2 -我没有将它们声明为json
解决方案: