如何将JSON数组解析为Struct

时间:2017-09-12 18:19:23

标签: rest go

给出以下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对象?

1 个答案:

答案 0 :(得分:1)

您已走上正轨,但更有用的解决方案是创建自定义解组器:

int system = 90; // rename this 
System.out.println(system);

现在,您可以直接将> sql = "SELECT StoreId,ProductCode,TotalQuantity FROM storeinvoicedetails \ WHERE StoreId = '%d' \ ORDER BY ProductCode ASC" % id 数据类型解组为:

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
}