在Go中的特定结构中解组Json数据 [英] Unmarshal Json data in a specific struct in Go
问题描述
b:= [] byte(`{询问 :[[21,1],[22,1]],投标:[[20,1],[19,1]]``
我知道如何做到这一点,我定义了一个像这样的结构体:
类型消息struct {
询问[] [] float64`json:出价`
出价[] [] float64`json:询问``
}
我不知道的是,是否有一种简单的方法来专门化
这一点。
我想在解组之后以这样的格式获得数据:
type消息struct {
询问[]订单`json:出价`
出价[]订单`json:询问``
}
类型订单结构{
Price float64
体积float64
}
这样我可以在解组后使用它像这样:
m:= new(Message)
err:= json.Unmarshal(b,& m )
fmt.Println(m.Asks [0] .Price)
t真的知道如何在GO
中轻松或惯用地做到这一点,所以我希望有一个很好的解决方案。
你可以通过执行 json.Unmarshaler
Order
结构。像这样的应该做的:$ b $ pre $
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
}
基本上说
你可以在这里玩这个例子: http://play.golang.org/p/B35Of8H1e6
I want to unmarshal the following JSON data in Golang:
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.
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
这篇关于在Go中的特定结构中解组Json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!