Unmarshal Json data in a specific struct

后端 未结 1 440
你的背包
你的背包 2020-12-15 08:07

I want to unmarshal the following JSON data in Go:

b := []byte(`{\"Asks\": [[21, 1], [22, 1]] ,\"Bids\": [[20, 1], [19, 1]]}`)

I know how t

相关标签:
1条回答
  • 2020-12-15 08:27

    You can do this with by implementing the json.Unmarshaler interface on your Order struct. Something like this should do:

    func (o *Order) UnmarshalJSON(data []byte) error {
        var v [2]float64
        if err := json.Unmarshal(data, &v); err != nil {
            return err
        }
        o.Price = v[0]
        o.Volume = v[1]
        return nil
    }
    

    This basically says that the Order type should be decoded from a 2 element array of floats rather than the default representation for a struct (an object).

    You can play around with this example here: http://play.golang.org/p/B35Of8H1e6

    0 讨论(0)
提交回复
热议问题