Search code examples
c#mongodbmongodb-.net-driver

How to serialize GUID properties as string in MongoDb?


I want to serialize a Dictionary<string, object> object in such a way that whenever the value is a Guid (or within the object graph of the value there is a Guid), the Guid is serialized as a string.

I tried running the following test:

Guid id = new ("11536e02-fcf3-4a8f-8b1d-ddfa6b4cee8a");
BsonSerializer.RegisterSerializer(new GuidSerializer(BsonType.String));
string json1 = BsonExtensionMethods.ToJson(id); // "11536e02-fcf3-4a8f-8b1d-ddfa6b4cee8a"
string json2 = BsonExtensionMethods.ToJson(new[] {id}); // ["11536e02-fcf3-4a8f-8b1d-ddfa6b4cee8a"]
string json3 = BsonExtensionMethods.ToJson(new {Id = id}); // { "Id": "11536e02-fcf3-4a8f-8b1d-ddfa6b4cee8a" }
string json4 = BsonExtensionMethods.ToJson(new Dictionary<string, object> {["Id"] = id}); // { "Id" : CSUUID("11536e02-fcf3-4a8f-8b1d-ddfa6b4cee8a") }

Everything works fine up to json4 which I expected to be identical to json3, but for some reason nested GUID values in dictionaries are still serialized in binary. How do I tell MongoDB to globally serialize all GUIDs as strings?


Solution

  • The problem is that the standard serializer for dictionaries in the MongoDB.Driver (observed in version 2.17.1) uses ObjectSerializer, which simply ignores the registered serializers for certain value types. This is arguably a bug. The workaround is to write and register your own serializers for dictionaries, arrays and objects.