2016-07-25 102 views
2

我想從Json生成一個Bson。我試過使用Json.Net,但似乎有一個記錄的行爲,其中庫生成uint64整數字段。不幸的是我們必須使用uint32。無法投入'MongoDB.Bson.BsonDocument'類型的對象來鍵入'MongoDB.Bson.BsonBinaryData'

因此,我試圖使用mongodb bson庫。但我不知道如何將BsonDocument轉換成BsonBinaryData。

//Works well, I can inspect with watch 
MongoDB.Bson.BsonDocument doc = MongoDB.Bson.BsonDocument.Parse(json); 

//Invalid cast exception 
byte[] data = doc.AsByteArray; 

回答

1

爲了得到一個BsonDocument實例的原始字節數組表示,使用該擴展方法ToBson()。要從字節數組表示形式創建BsonDocument,請創建一個RawBsonDocument的實例,該實例從BsonDocument派生,並將字節數組作爲構造函數參數。

下面是使用兩個BSON文件參數傳遞到本地C函數調用和檢索結果的一個例子:

public static BsonDocument CallCFunction(BsonDocument doc) { 
    byte[] input = doc.ToBson(); 
    int length = input.Length; 
    IntPtr p = DllImportClass.CFunction(ref length, input); 
    if (p == IntPtr.Zero) { 
    // handle error 
    } 
// the value of length is changed in the c function 
    var output = new byte[length]; 
    System.Runtime.InteropServices.Marshal.Copy(p, output, 0, length); 
    return new RawBsonDocument(output); 
} 

注意,要必須以某種方式被釋放的內存p點。

+0

令人印象深刻的是,您分享的這些信息不容易找到!這足夠了,直到現在我還找不到這樣簡單的解決方案(搜索幾天),寫一篇很容易被人們搜索到的帖子!非常感謝 – Ibrahim

相關問題