Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-2643

Automapped serializer for anonymous classes should use default values for missing elements when deserializing

    • Type: Icon: Task Task
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 2.9.0
    • Affects Version/s: 2.8.1
    • Component/s: Serialization
    • Labels:
      None

      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);
              }
          }
      }
      
      

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            robert@mongodb.com Robert Stam
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: