2016-11-17 102 views
0

我用我golang项目走,杜松子酒服务器,并取出由返回数组作为响应如何拦截在数组中的REST API响应去,杜松子酒

[ 
    { 
    "Continent": "South America", 
    "Countries": [ 
     { 
     "Country": "Argentina" 
     } 
    ] 
    } 
] 

在外部API的一些数据我这里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

的可能的复制[如何获得JSON响应Golang](http://stackoverflow.com/questions/17156371/how-to-get-json-response-in-golang) – Carpetsmoker

+0

我试过这个。添加更多详细信息 – aaj

+0

您的JSON不代表字符串数组。尝试'输入target [] interface {}'。 –

回答

1

您的第一个示例不起作用,因为您试图将字符串编组为JSON,它只会转义字符串。 相反,最后一行改为

c.String(200, string(respbody)) 

这不会改变您从第三方在所有接收的字符串,将刚刚返回。请参阅here

如果要检查数据,因为它穿过你的程序,您必须将JSON字符串首先解码成结构数组是这样的:

type Response []struct { 
    Continent string `json:"Continent"` 
    Countries []struct { 
     Country string `json:"Country"` 
    } `json:"Countries"` 
} 
相关问题