我在我的golang项目中使用go-gin服务器,并从一个外部API获取一些数据,该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))这会给出currect响应,但我得到的不是数组,而是包含整个数组的字符串。所以我得到的回答是
"[{\"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{})发布于 2016-11-17 22:39:12
第一个示例不起作用,因为您试图将一个字符串编组为只对字符串进行转义的JSON。相反,将最后一行更改为
c.String(200, string(respbody))这根本不会改变你从第三方收到的字符串,而只是返回它。有关区别,请参阅here。
如果您希望在数据通过程序时对其进行检查,则必须首先将JSON字符串解码为一个结构数组,如下所示:
type Response []struct {
Continent string `json:"Continent"`
Countries []struct {
Country string `json:"Country"`
} `json:"Countries"`
}https://stackoverflow.com/questions/40652375
复制相似问题