简体   繁体   English

在特定结构中解组Json数据

[英]Unmarshal Json data in a specific struct

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中如何轻松或惯用,所以我希望有一个很好的解决方案。

You can do this with by implementing the json.Unmarshaler interface on your Order struct. 您可以通过在Order结构上实现json.Unmarshaler接口来完成此操作 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). 这基本上表示Order类型应该从2元素浮点数组中解码,而不是结构(对象)的默认表示。

You can play around with this example here: http://play.golang.org/p/B35Of8H1e6 你可以在这里玩这个例子: http//play.golang.org/p/B35Of8H1e6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM