Reputation: 6741
I'm using DictionaryRepresentation.ArrayOfDocuments for serializing a dictionary field in my object.
By default, the key/value fields names are "k","v".
Is there a way to change them to "Key", "Value"?
Documentation: mongo-csharp-driver/1.11/serialization/
Upvotes: 1
Views: 337
Reputation: 6741
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.
The generated Bson isn't Mongo's custom one so it won't contain specific features like discriminator fields and such.
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;
}
}
Upvotes: 1