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

Dictionary can't be serialized as a document

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 2.0
    • Component/s: BSON, Serialization
    • None

      In the new version, dictionaries are serialized (unless specified otherwise) as a document which isn't backwards compatible in some cases, for example this class:

          public class Hamster
          {
              public ObjectId Id { get; private set; }
              public Dictionary<IPAddress, string> Dictionary { get; private set; }
              public Hamster()
              {
                  Id = ObjectId.GenerateNewId();
                  Dictionary = new Dictionary<IPAddress, string>();
                  Dictionary[IPAddress.Parse("8.8.8.8")] = "";
              }
          }
      

      In v1.9 `Dictionary` is serialized just fine as a an array of arrays, but in v2.0 serializing this would throw the following exception:

      MongoDB.Bson.BsonSerializationException: Element name '8.8.8.8' is not valid.

      This can be solved by adding an attribute:

      [BsonDictionaryOptions(Representation = DictionaryRepresentation.ArrayOfArrays)]
      public Dictionary<IPAddress, string> Dictionary { get; private set; }
      

      But as far as I know this needs to be done on a case by case basis as there isn't a relevant convention pack

            Assignee:
            Unassigned Unassigned
            Reporter:
            I3arnon Bar Arnon
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: