[CSHARP-1675] ObjectSerializer ignores registered DateTime serializer on deserializing Created: 22/May/16  Updated: 08/Dec/20  Resolved: 08/Dec/20

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Maksim Simkin Assignee: Boris Dogadov
Resolution: Won't Fix Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Test to reproduce:
-register DateTimeSerializer with local Kind
-Serialize DateTime (local Kind) as object
-Deserialize it.

        public class ObjectClass
        {
            public object Value { get; set; }
        }
 
        [SetUp]
        public void Register()
        {
            var serializer = new Bson.Serialization.Serializers.DateTimeSerializer(DateTimeKind.Local);
            BsonSerializer.RegisterSerializer(typeof(DateTime), serializer);
        }
 
        [Test]
        public void RegisterTest()
        {
 
            var dt = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Local);
            var o = new ObjectClass { Value = dt };
 
            var serilized = o.ToJson();
            var restored = BsonSerializer.Deserialize<ObjectClass>(serilized);
 
            Assert.AreEqual(dt, restored.Value);
            Assert.AreEqual(dt.Kind, ((DateTime)restored.Value).Kind);
        }



 Comments   
Comment by Boris Dogadov [ 08/Dec/20 ]

Thank you for finding this issue and submitting a fix. Typically when serializing/deserializing POCOs, the types of the properties and fields are explicitly specified. The issue only manifests when the type of a property or field is specified as System.Object and the actual underlying type has direct mapping to BSON type (like DateTime). For other types the registered serializers will be used.

This issue can be mitigated by:
1. Specifying the explicit type of the property or field (if possible).
2. Registering a custom serializer for the containing type.

Although your fix appears simple, it alters the serialization/deserialization of existing types and may unexpectedly break applications depending on current serialization behaviour. As such we consider it too risky of a change to be implemented without deeper consideration. We will consider this use case and fix in some upcoming work to improve our serialization infrastructure.

Generated at Wed Feb 07 21:40:21 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.