使用mongodb和c#驱动程序,如何将json反序列化为匿名类型
本文关键字:反序列化 json 类型 mongodb 驱动程序 使用 | 更新日期: 2023-09-27 18:02:26
我需要将字符串反序列化回匿名类型/对象,但我得到:
A document being deserialized to System.Object must be empty.
有办法做到这一点吗?保存文档很好,只是在试图反序列化它时遇到了问题。代码如下:
[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; }
}
当前版本的驱动程序似乎无法反序列化匿名类型