[CSHARP-2643] Automapped serializer for anonymous classes should use default values for missing elements when deserializing Created: 19/Jun/19  Updated: 28/Oct/23  Resolved: 25/Jun/19

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

Type: Task Priority: Major - P3
Reporter: Robert Stam Assignee: Robert Stam
Resolution: Fixed Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by CSHARP-1339 Adding array member to collection mod... Closed

 Description   

Serializers for anonymous types are created automatically with little or no chance of user configuration of the serializer. Currently, the automatically created serializer requires that the document being deserialized contain an element for every property of the anonymous class.

It would be desirable for the serializer for an anonymous class to simply use default values for any missing elements rather than throw an exception.

This is a little tricky to reproduce because it involves anonymous classes, but the following code using a generic local function reproduces the issue. Ideally all 4 JSON inputs would be successfully deserialized.

 

public static class Program
{
    public static void Main(string[] args)
    {
        var prototype = new { X = 1, Y = 2 };
 
        T deserialize<T>(T dummy, string json)
        {
            var serializer = BsonSerializer.LookupSerializer<T>();
            using (var reader = new JsonReader(json))
            {
                var context = BsonDeserializationContext.CreateRoot(reader);
                return serializer.Deserialize(context);
            }
        }
 
        var inputs = new[] { "{ }""{ X : 3 }""{ Y :  4 }""{ X : 3, Y :  4 }" };
        foreach (var json in inputs)
        {
            var a = deserialize(prototype, json);
        }
    }
}



 Comments   
Comment by Githook User [ 25/Jun/19 ]

Author:

{'name': 'rstam', 'username': 'rstam', 'email': 'robert@robertstam.org'}

Message: CSHARP-2643: Automapped serializer for anonymous classes should use default values for missing elements when deserializing.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/fad2887cd28950ebb50d1039e336026d1f169339

Comment by Rufus Houston [ 20/Jun/19 ]

Thank you for the update. We will keep watching

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