问题描述
我想在 Go 中解组以下 JSON 数据:
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 to do that, i define a struct like this:
type Message struct {
Asks [][]float64 `json:"Bids"`
Bids [][]float64 `json:"Asks"`
}
我不知道是否有一种简单的方法可以专门化这有点多.我希望解组后的数据采用如下格式:
What i don't know is if there is a simple way to specializethis a bit more.I would like to have the data after the unmarshaling in a format like this:
type Message struct {
Asks []Order `json:"Bids"`
Bids []Order `json:"Asks"`
}
type Order struct {
Price float64
Volume float64
}
这样我就可以在像这样解组后使用它:
So that i can use it later after unmarshaling like this:
m := new(Message)
err := json.Unmarshal(b, &m)
fmt.Println(m.Asks[0].Price)
我真的不知道如何在 GO 中轻松或惯用地做到这一点所以我希望有一个很好的解决方案.
I don't really know how to easy or idiomatically do that in GOso I hope that there is a nice solution for that.
推荐答案
您可以通过实施 json.Unmarshaler
interface 在您的 Order
结构上.应该这样做:
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
}
这基本上是说 Order
类型应该从浮点数的 2 元素数组而不是结构(对象)的默认表示中解码.
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).
你可以在这里玩这个例子:http://play.golang.org/p/B35Of8H1e6
You can play around with this example here: http://play.golang.org/p/B35Of8H1e6
这篇关于在特定结构中解组 Json 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!