在特定结构中解组 Json 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26511417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unmarshal Json data in a specific struct
提问by ungchy
I want to unmarshal the following JSON data in Go:
我想在 Go 中解组以下 JSON 数据:
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 specialize this 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)
I don't really know how to easy or idiomatically do that in GO so I hope that there is a nice solution for that.
我真的不知道如何在 GO 中轻松或惯用地做到这一点,所以我希望有一个很好的解决方案。
回答by James Henstridge
You can do this with by implementing the json.Unmarshalerinterfaceon your Orderstruct. Something like this should do:
您可以通过在结构上实现json.Unmarshaler接口来做到这一点Order。这样的事情应该做:
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 Ordertype should be decoded from a 2 element array of floats rather than the default representation for a struct (an object).
这基本上是说Order应该从浮点数的 2 元素数组而不是结构(对象)的默认表示中解码类型。
You can play around with this example here: http://play.golang.org/p/B35Of8H1e6
你可以在这里玩这个例子:http: //play.golang.org/p/B35Of8H1e6

