我有以下JSON数据:
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "960.094",
"price_btc": "1.0",
"24h_volume_usd": "438149000.0",
"market_cap_usd": "15587054083.0",
"available_supply": "16234925.0",
"total_supply": "16234925.0",
"percent_change_1h": "-0.76",
"percent_change_24h": "-7.78",
"percent_change_7d": "-14.39",
"last_updated": "1490393946"
}
]我有两个结构:
type Valute struct {
Id string `json:"id"`
Name string `json:"name"`
Symbol string `json:"symbol"`
}
type Currency struct {
Result []Valute
}我想解析这个调用返回的数组:
resp, err := http.Get("https://api.coinmarketcap.com/v1/ticker/?limit=1")
defer resp.Body.Close()
v := Currency{}
body, err := ioutil.ReadAll(resp.Body)
json.Unmarshal(body, &v)但这对我不起作用。货币是空的。
它与一个数组一起工作:
var valutes []Valute
json.Unmarshal(body, &valutes)但我想用一个结构。
发布于 2017-03-25 07:46:50
您的货币结构只需实现json.Unmarshaler接口即可。
func (c *Currency) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &c.Result)
}发布于 2017-03-25 09:25:28
您也可以更改为json.Unmarshal(body, &v.Result)
https://stackoverflow.com/questions/43013758
复制相似问题