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

    XMLWordPrintableJSON

Details

    • Icon: Task Task
    • Resolution: Fixed
    • Icon: Major - P3 Major - P3
    • 2.9.0
    • 2.8.1
    • Serialization
    • None

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

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated:
              Resolved: