skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. Your dictionary is created as <string, object>, so effectively a type you use is object, not Guid, to fix it, set Guid generic type explicitly:

    string json4 = BsonExtensionMethods.ToJson(new Dictionary<string, Guid> { ["Id"] = id });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search