Ricardo Peres
Ricardo Peres

Reputation: 14535

Deserializing a C# Dictionary in MongoDB Returns Null

I have a simple class:

public class Foo
{
    public ObjectId Id { get; set; }
    public Dictionary<string, object> Bar { get; set; }
}

Nothing else, no custom mappings, etc. When I insert it into MongoDB, it works perfectly, but the Bar property is ignored, although, at insertion time, it is not null. I tried adding [BsonDictionaryOptions] and [BsonElement] but these had no effect.

Upvotes: 1

Views: 759

Answers (2)

profesor79
profesor79

Reputation: 9473

for a test purposes I added to class Foo

[BsonDictionaryOptions]
public Dictionary<string, object> Bar = new Dictionary<string, object>() { 
           { "1", new object() }, 
           { "2", new object() } };

when dictionary is empty - the field is empty, but when we are sending data in it - it reflects inserted data.

{
        "_id" : ObjectId("56d9b9e4c875835548bc62de"),
        "Bar" : {
                "1" : {

                },
                "2" : {

                }
        }
} 

and when we have:

 public Dictionary<string, string> Bar =
      new Dictionary<string, string>() { { "1", "text" }, { "2", "text" } };

then output is:

"_id" : ObjectId("56d9bb5ac875835548bc62df"), "Bar" : { "1" : "text", "2" : "text" }

Upvotes: 1

Ricardo Peres
Ricardo Peres

Reputation: 14535

The problem is solved: I was using a custom serializer inadvertently.

Upvotes: 1

Related Questions