英文:
Unmarshal Json data in a specific struct
问题
我想在Go中解析以下JSON数据:
b := []byte(`{"Asks": [[21, 1], [22, 1]], "Bids": [[20, 1], [19, 1]]}`)
我知道如何做到这一点,我定义了一个如下的结构体:
type Message struct {
Asks [][]float64 `json:"Bids"`
Bids [][]float64 `json:"Asks"`
}
我不知道的是是否有一种简单的方法来进一步专门化这个结构体。我希望在解析后的数据中以以下格式呈现:
type Message struct {
Asks []Order `json:"Bids"`
Bids []Order `json:"Asks"`
}
type Order struct {
Price float64
Volume float64
}
这样,我可以在解析后的数据中稍后使用,例如:
m := new(Message)
err := json.Unmarshal(b, &m)
fmt.Println(m.Asks[0].Price)
我不太清楚如何在Go中以简单或习惯的方式做到这一点,所以我希望有一个好的解决方案。
英文:
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 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.
答案1
得分: 24
你可以通过在你的Order
结构体上实现json.Unmarshaler
接口来实现这个功能。像下面这样做:
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
类型从一个包含两个浮点数的数组解码,而不是默认的结构体表示(一个对象)。
你可以在这里尝试这个例子:http://play.golang.org/p/B35Of8H1e6
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论