duancan2539 2014-10-22 15:37
浏览 20
已采纳

在特定结构中解组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 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条回答 默认 最新

  • doumeng3345 2014-10-22 15:55
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址