doulun7739 2017-11-16 03:49
浏览 148
已采纳

在Go中,如何将bson byte []数据解组为结构数组?

What's the best way to Unmarshal bson byte[] data into an array of structs, when the array of structs is passed into an interface{} parameter?

For demonstration purposes, in the following code, I use bson.Marshal() on the inStructArr to get the byte[] type of data. This is so I can use bson.Unmarshal(...) to pipe into the outStructArr.

import "gopkg.in/mgo.v2/bson"

type User struct {
    Name string
}

func DecodeArrData(inStructArr, outStructArr interface{}) {
    inStructArrData, _ := bson.Marshal(inStructArr)
    bson.Unmarshal(inStructArrData, outStructArr) // <-- Error happens here
    // What's the right way of accomplishing this?
}

func Main() {
    outUsers := &[]User{}
    inUsers := []User{User{"A"}, User{"B"}}

    DecodeArrData(inUsers, outUsers)
}

When I do this, the error-message I get is: Unsupported document type for unmarshalling: []User. What's the right way of doing this?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dqdtgiw4736 2017-11-16 07:47
    关注

    The Marshal and Unmarshal functions work with BSON documents, not BSON arrays.

    Wrap the slices in a struct to provide the document expected by the package:

    func DecodeArrData(inStructArr, outStructArr interface{}) error {
        in := struct{ Data interface{} }{Data: inStructArr}
        inStructArrData, err := bson.Marshal(in)
        if err != nil {
            return err
        }
        var out struct{ Data bson.Raw }
        if err := bson.Unmarshal(inStructArrData, &out); err != nil {
            return err
        }
        return out.Data.Unmarshal(outStructArr)
    }
    

    If you are willing to take advantage of an undocumented feature of the Marshal function and add some BSON format knowledge to your application, then you can omit the wrapper.

    The undocumented feature of Marshal is that it encodes slices as BSON arrays. The BSON array can be decoded using a bson.Raw value with Kind set the the BSON code for arrays (the value 4) and Data set to the array data:

    func DecodeArrData(inStructArr, outStructArr interface{}) error {
        inStructArrData, err := bson.Marshal(inStructArr)
        if err != nil {
            return err
        }
        raw := bson.Raw{Kind: 4, Data: inStructArrData}
        return raw.Unmarshal(outStructArr)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集