簡體   English   中英

在 MongoDb 字典 bson 序列化(C# 驅動程序)中更改鍵/值字段的名稱

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

我正在使用 DictionaryRepresentation.ArrayOfDocuments 來序列化對象中的字典字段。
默認情況下,鍵/值字段名稱為“k”、“v”。
有沒有辦法將它們更改為“鍵”、“值”?

文檔: mongo-csharp-driver/1.11/serialization/

如果您對 MongoDb 驅動程序提供的 C#/Bson 序列化選項不感興趣,一種選擇是使用 Newtonsoft bson writer,然后使用 MongoDb reader 讀取 bson。
生成的 Bson 不是 Mongo 自定義的,因此它不會包含特定的特征,如鑒別器字段等。 例子:

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