假设这是 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/