.net - 无法将类型为 'MongoDB.Bson.BsonDocument' 的对象转换为类型 'MongoDB.Bson.BsonBinaryData'

标签 .net mongodb bson

我正在尝试从 Json 生成 Bson。我尝试使用 Json.Net,但似乎有记录的行为,其中库为整数字段生成 uint64。不幸的是,我们必须使用 uint32。

因此我正在尝试使用 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;

最佳答案

要获取 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 指向的内存必须以某种方式释放。

关于.net - 无法将类型为 'MongoDB.Bson.BsonDocument' 的对象转换为类型 'MongoDB.Bson.BsonBinaryData',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38569317/

相关文章:

javascript - Mongoose 和字段类型 - 数字返回对象,字符串返回字符串?

javascript - ExpressJS 中最好的 session 存储 - NodeJS

c# - 使用 Mongo C# 驱动程序序列化不可变值类型

python - 如何将 CodecOptions 应用于 mongoengine 集合以获取 tzinfo?

c# - 有没有比Environment.StackTrace更简洁的方法来获取调用堆栈信息?

javascript - RadGrid 上的 get_selectedItems()[0] 返回 null

node.js - 如何对 Mongoose 中的结果数组进行排序和限制?

c# - C# 驱动程序中的 MongoDB 评估查询表达式

c# - 从字典中获取除 "foreach"之外的键和值

c++ - 使用 C++ 遗留驱动程序的 mongodb 查询导致 BSONElement : bad type -64