简体   繁体   English

在 MongoDb 字典 bson 序列化(C# 驱动程序)中更改键/值字段的名称

[英]Changing key / value fields' name in MongoDb dictionary bson serialization (C# driver)

I'm using DictionaryRepresentation.ArrayOfDocuments for serializing a dictionary field in my object.我正在使用 DictionaryRepresentation.ArrayOfDocuments 来序列化对象中的字典字段。
By default, the key/value fields names are "k","v".默认情况下,键/值字段名称为“k”、“v”。
Is there a way to change them to "Key", "Value"?有没有办法将它们更改为“键”、“值”?

Documentation: mongo-csharp-driver/1.11/serialization/文档: mongo-csharp-driver/1.11/serialization/

If you are not interested in the C#/Bson serialization options MongoDb driver offer, one option is using Newtonsoft bson writer and then read the bson with MongoDb reader.如果您对 MongoDb 驱动程序提供的 C#/Bson 序列化选项不感兴趣,一种选择是使用 Newtonsoft bson writer,然后使用 MongoDb reader 读取 bson。
The generated Bson isn't Mongo's custom one so it won't contain specific features like discriminator fields and such.生成的 Bson 不是 Mongo 自定义的,因此它不会包含特定的特征,如鉴别器字段等。 Example:例子:

class DictionaryAsArrayResolver : DefaultContractResolver
    {
        protected override JsonContract CreateContract(Type objectType)
        {
            if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) || 
                                                    (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
            {
                return base.CreateArrayContract(objectType);
            }
    
            return base.CreateContract(objectType);
        }
    }

    class BsonDocBuilder
    {
        private readonly MemoryStream _memStream = new MemoryStream();
        private readonly JsonSerializerSettings _serializeSettings = new JsonSerializerSettings();
        private readonly JsonSerializer _jsonSerializer; 
        public BsonDocBuilder()
        {
            _serializeSettings.ContractResolver = new DictionaryAsArrayResolver();    
            _jsonSerializer = JsonSerializer.Create(_serializeSettings);
        }

        public BsonDocument ToBson<T>(T value)
        {
            BsonDocument bd;
            try
            {
                using (BsonDataWriter dataWriter = new BsonDataWriter(_memStream))
                {
                    dataWriter.CloseOutput = false;
                    _jsonSerializer.Serialize(dataWriter, value);
                }
                bd= BsonSerializer.Deserialize<BsonDocument>(_memStream.ToArray());
            }
            finally
            {
                _memStream.SetLength(0);                    
            }

            return bd;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM