我在golang项目中使用go-gin服务器并从外部API获取一些数据,这些数据返回一个数组作为响应
[
{
"Continent": "South America",
"Countries": [
{
"Country": "Argentina"
}
]
}
]
在我的golang代码中,这里是我发送请求和拦截响应的方式
client := &http.Client{Transport: tr}
rget, _ := http.NewRequest("GET", "http://x.x.x.x/v1/geodata", nil)
resp, err := client.Do(rget)
if err != nil {
fmt.Println(err)
fmt.Println("Failed to send request")
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
c.Header("Content-Type", "application/json")
c.JSON(200, string(respbody))
这给出了当前的响应,但是我得到一个包含整个数组的字符串而不是数组。所以我得到的回应是
"[{\"Continent\":\"South America\",\"Countries\": [{\"Country\": \"Argentina\"} ] } ]"
如何拦截响应为数组而不是字符串? 我甚至试过以下哪个确实给了我一个数组但是空白的数组。我的响应主体中的元素可能是数组和字符串,因此内容是混合的。
type target []string
json.NewDecoder(resp.Body).Decode(target{})
defer resp.Body.Close()
c.Header("Content-Type", "application/json")
c.JSON(200, target{})
答案 0 :(得分:1)
你的第一个例子不起作用,因为你试图将一个字符串编组为JSON,它只会转义字符串。 而是将最后一行更改为
c.String(200, string(respbody))
这根本不会改变您从第三方收到的字符串,只会将其退回。有关差异,请参阅here。
如果要在数据通过程序时检查数据,则必须首先将JSON字符串解码为结构数组,如下所示:
type Response []struct {
Continent string `json:"Continent"`
Countries []struct {
Country string `json:"Country"`
} `json:"Countries"`
}