Question

I need to deserialize a string back to an anonymous type/object but am getting:

A document being deserialized to System.Object must be empty.

Is there a way to do this? Saving the doc is fine, just have issues trying to deserialize it. Code below:

[TestFixture]
public class ObjectTests
{
    [Test]
    public void Can_Deserialize_To_Object()
    {
        BsonDefaults.GuidRepresentation = GuidRepresentation.CSharpLegacy;
        BsonClassMap.RegisterClassMap<Thing>(x =>
        {
            x.AutoMap();
            x.SetIdMember(x.GetMemberMap(c => c.Id));
        });

        var client = new MongoClient("mongodb://localhost").GetServer().GetDatabase("Test");

        var things = client.GetCollection<Thing>("Things");
        things.Drop();

        var thing = new Thing();
        thing.Data = new
        {
            Text = "This is some text",
            Value = "This is the value"
        };
        things.Insert(thing);

        // System.IO.FileFormatException : An error occurred while deserializing the Data property of class Soma.Core.Tests.Thing: A document being deserialized to System.Object must be empty.
       var result = things.FindOne();

    }
}

public class Thing
{
    public Guid Id { get; set; }
    public object Data { get; set; }
}
Was it helpful?

Solution

Seems current version of the driver cannot deserialize anonymous types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top