字典<字符串,对象>至BsonDocument的转换省略了_t字段 [英] Dictionary<string, object>-to-BsonDocument conversion omitting _t field

查看:93
本文介绍了字典<字符串,对象>至BsonDocument的转换省略了_t字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB.Bson中的ToBsonDocument扩展方法来转换此词典:

I'm using ToBsonDocument extension method from MongoDB.Bson to convert this Dictionary:

        var dictionary = new Dictionary<string, object> {{"person", new Dictionary<string, object> {{"name", "John"}}}};
        var document = dictionary.ToBsonDocument();

这是生成的文档:

  { "person" : 
      { "_t" : "System.Collections.Generic.Dictionary`2[System.String,System.Object]", 
        "_v" : { "name" : "John" } } }

是否有办法摆脱这些_t/_v东西?我希望生成的文档看起来像这样:

Is there a way to get rid of these _t/_v stuff? I would like the resulting document to look like this:

  { "person" : { "name" : "John" } }


UPD:我在DictionaryGenericSerializer中找到了代码:


UPD: I've found the code in 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;
}

因此,当值类型为object时,此序列化程序似乎没有太多选项.

So, it seems that there are not too many options with this serializer when the value type is object.

推荐答案

您应首先序列化为JSON,然后序列化为BSON,

You shall first serialize to JSON and then to BSON,

var jsonDoc = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);
var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonDoc);

这篇关于字典&lt;字符串,对象&gt;至BsonDocument的转换省略了_t字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆