【发布时间】:2018-06-13 08:56:51
【问题描述】:
我正在尝试使用 Golang 将来自 API 的响应映射到结构。
当我在浏览器中查看链接时返回的 JSON 如下:
{
"GBP": 657.54
}
我只想将它映射到一个简单的结构,如下所示:
type Price struct {
Name string
Value float64
}
这是我当前的代码。
func FetchCoinPrice(fsym string, tsyms string) Price {
url := fmt.Sprintf("https://min-api.cryptocompare.com/data/price?fsym=" + fsym + "&tsyms=" + tsyms)
fmt.Println("Requesting data from " + url)
price := Price{}
// getting the data using http
request, err := http.Get(url)
if err != nil {
log.Fatal(err.Error())
}
// Read the response body using ioutil
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Fatal(err.Error())
}
defer request.Body.Close()
if request.StatusCode == http.StatusOK {
json.Unmarshal(body, &price)
}
return price
}
目前我收到的只是一个空结构,我知道该链接正在返回正确的数据,并且我已经在浏览器中对其进行了测试。
【问题讨论】:
-
这是两种不同的数据结构。如果要将值复制到不同的结构中,则必须手动执行。
-
你必须使用一些 dynamic 来模拟你的 dynamic 输入。查看可能的重复项:How to parse/deserlize a dynamic JSON in Golang;和Unmarshal json string to a struct that have one element of the struct itself。
标签: go