作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
给定以下 REST 调用...
https://api.bitfinex.com/v2/ticker/fUSD
...我得到以下结果作为 JSON 数组:
[0.00073995,0.00067,30,10082128.5775703,0.000664,2,191337.1001453,-0.00003991,-0.057,0.00066009,94710166.80102274,0,0]
下面是我解析结果的方式:
const (
URL = "https://api.bitfinex.com/v2/ticker/f"
)
type Tick struct {
FlashReturnRate float64
Bid float64
BidPeriod int64
BidSize float64
Ask float64
AskPeriod int64
AskSize float64
DailyChange float64
DailyChangePerc float64
LastPrice float64
Volume float64
High float64
Low float64
}
...
func (s *TickerService) Get(curry string) (*Tick, error) {
req, err = http.NewRequest("GET", URL + curry, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req); if err != nil {
return nil, err
}
defer resp.Body.Close()
var v []float64
err = json.Unmarshal(resp.Body, &v)
if err != nil {
return nil, err
}
t := Tick{
FlashReturnRate: v[0],
Bid: v[1],
BidSize: v[2],
BidPeriod: int64(v[3]),
Ask: v[4],
AskSize: v[5],
AskPeriod: int64(v[6]),
DailyChange: v[7],
DailyChangePerc: v[8],
LastPrice: v[9],
Volume: v[10],
High: v[11],
Low: v[12],
}
return &t, nil
}
有没有更好的方法来构建 Tick
对象?
最佳答案
您走在正确的轨道上,但更有用的解决方案是创建自定义解码器:
func (t *Tick) UnmarshalJSON(data []byte) error {
var v []float64
if err := json.Unmarshal(data, &v); err != nil {
return err
}
t.FlashReturnRate = v[0]
t.Bid = v[1]
t.BidSize = int64(v[2]) // Is this an int? Your sample data suggests it is, your code suggests it isn't.
// ... etc
return nil
}
现在您可以直接解码为您的 Tick
数据类型:
var tick Tick
if err := json.Unmarshal(res.Body, &tick); err != nil {
// Handle error
}
关于rest - 如何将 JSON 数组解析为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183083/
我是一名优秀的程序员,十分优秀!