vor*_*rou 8 c# dictionary mongodb bson
我正在使用ToBsonDocument扩展方法MongoDB.Bson来转换这个字典:
var dictionary = new Dictionary<string, object> {{"person", new Dictionary<string, object> {{"name", "John"}}}};
var document = dictionary.ToBsonDocument();
Run Code Online (Sandbox Code Playgroud)
这是结果文件:
{ "person" :
{ "_t" : "System.Collections.Generic.Dictionary`2[System.String,System.Object]",
"_v" : { "name" : "John" } } }
Run Code Online (Sandbox Code Playgroud)
有没有办法摆脱这些_t/_v的东西?我希望生成的文档看起来像这样:
{ "person" : { "name" : "John" } }
Run Code Online (Sandbox Code Playgroud)
UPD:我在DictionaryGenericSerializer中找到了代码:
if (nominalType == typeof(object))
{
var actualType = value.GetType();
bsonWriter.WriteStartDocument();
bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType));
bsonWriter.WriteName("_v");
Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType
bsonWriter.WriteEndDocument();
return;
}
Run Code Online (Sandbox Code Playgroud)
因此,当值类型为时,似乎没有太多选项可用于此序列化程序object.
sel*_*van 13
您应首先序列化为JSON,然后序列化为BSON,
var jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);
var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonDoc);
Run Code Online (Sandbox Code Playgroud)
这是因为您object为字典值指定了类型,但实际上Dictionary<string, object>对特定记录值使用了类型。因此,CSharp 驱动程序保存了具体类型的全名,以便将来正确反序列化此文档。您还可以在此处阅读更多相关信息:使用 CSharp 驱动程序序列化文档:多态类和鉴别器
要获得所需的结果,您应该为字典值指定具体类型:
var dictionary = new Dictionary<string, Dictionary<string, object>>
{
{ "person", new Dictionary<string, object> { { "name", "John" } } }
};
var document = dictionary.ToBsonDocument();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10719 次 |
| 最近记录: |