我正在使用JsonConvert
来序列化和反序列化来自此类的对象,如下所示:
public class DbBulkRequest
{
public DbEntity[] Updates { get; set; }
}
public class DbEntity
{
public string Name { get; set; }
public object Dto { get; set; }
}
当我反序列化Dto
时,我得到一个类型为 JObject
的对象。在反序列化时,我想基于 Dto
创建强类型对象。我可以创建对象;但是,我不知道填充其属性的好方法。我发现的最好的是这种芝士球方法:
MyEntity e = JsonConvert.DeserializeObject<MyEntity>(JsonConvert.SerializeObject(dto));
什么是更有效的解决方案?
添加TypeNameHandling
private readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto
};
这是一个例子
private readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto
};
[Fact]
public void Test()
{
var entity = new DbEntity
{
Dto = new TestDto { Value = "dto" },
Name = "Entity"
};
string serializedObject = JsonConvert.SerializeObject(entity, defaultSettings);
var deserializedObject = JsonConvert.DeserializeObject<DbEntity>(serializedObjest, defaultSettings);
}
public class DbBulkRequest
{
public DbEntity[] Updates { get; set; }
}
public class DbEntity
{
public object Dto { get; set; }
public string Name { get; set; }
}
public class TestDto
{
public string Value { get; set; }
}