我正在使用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));
什么是更有效的解决方案?
答案 0 :(得分:3)
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; }
}