c# - 反序列化嵌套和非结构化 BsonDocument(mongodb c# 驱动程序)

标签 c# mongodb mongodb-.net-driver

假设这是 2 个 Bson 文档的集合

{
    "_id": "...",
    "name": "Test1",
    "sub": {
        "street": "134 Fake Street",
        "city": "NoWhere"
    }
},
{
    "_id": "...",
    "name": "Test2",
    "sub": {
        "height": "10",
        "width": "20",
        "sub2": {
            "type": "something"
        }
    }
}

其中第一级是结构化类,但子级可以完全非结构化,并且可以进一步嵌套多个级别的文档。

如何将此文档反序列化为 C# 类?我见过的所有示例都假设嵌套文档中存在某种结构。

以下类给出错误:

public class Report
{
    [BsonId]
    public ObjectId _id { get; set; }

    public string name { get; set; }

    public BsonDocument sub { get; set; }
}

Type 'MongoDB.Bson.BsonString' with data contract name '...' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

编辑

我想做的事情可能完全是无意义的。仅使用一个 BsonDocument 并在没有结构化类的情况下手动处理所有内容是一个更好的主意吗?

最佳答案

我认为您收到的错误消息不是来自 C# 驱动程序。您能提供堆栈跟踪吗?

我已尝试重现您的问题,但它在我的测试程序中运行良好。

上面的测试程序插入的文档如下所示:

> db.test.find()
{ "_id" : ObjectId("5075fc6ee447ad1354c1f018"), "name" : "John Doe", "sub" : { "x" : 1, "y" : 2 } }
>

关于c# - 反序列化嵌套和非结构化 BsonDocument(mongodb c# 驱动程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12796705/

相关文章:

c# - 使用 Windows 文件复制或文件移动动画?

c# - 隐藏我的网站是用 ASP.NET 构建的事实

c# - json.net 有关键方法吗?

node.js - 在大型 Mongo 集合中,如何使用 mongoose 仅​​检索 ID(或任何其他特定属性)?

mongodb - 使用 C# 将嵌套文档插入到 MongoDB 中

c# - 使用 LINQ 列出(和返回)的列

perl - 使用 Mango 时 morbo 的导入/导出错误

node.js - MongoDB/mongoose 在两个模型之间创建关系?

mongodb - 在 mongodb c# 驱动程序中设置 DateTimeSerializationOptions.Defaults 的新方法是什么?

C# - 使用 NoSQL (MongoDB) 生成类似 Id 的 "identity"?