字典<string,object> -to-BsonDocument转换省略_t字段

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)


Sha*_*had 6

这是因为您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)

  • 是的,如果我为值指定具体类型,它就可以正常工作。但在我的例子中,任何值都可以是一个 `string` 值或另一个 `Dictionary`。因此,对于该类型,我似乎不能使用除 `object` 以外的任何其他内容。在这种情况下,我可以以某种方式要求司机表现得一样吗? (2认同)