将JObject转换为强类型对象 [英] Convert a JObject to a strongly typed object
本文介绍了将JObject转换为强类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用JsonConvert
从这样的类对对象进行序列化和反序列化:
I'm using JsonConvert
to serialize and deserialize objects from classes like this:
public class DbBulkRequest
{
public DbEntity[] Updates { get; set; }
}
public class DbEntity
{
public string Name { get; set; }
public object Dto { get; set; }
}
反序列化Dto
时,会得到一个JObject
类型的对象.在反序列化时,我想基于Dto
创建强类型的对象.我可以创建对象;但是,我不知道填充其属性的好方法.我发现最好的就是这种芝士球方法:
When I deserialize Dto
, I get an object of type JObject
. At the time of deserialization, I want to create strongly typed objects based on Dto
. I can create the objects; however, I don't know of a good way of populating their properties. The best I've found is this cheeseball approach:
MyEntity e = JsonConvert.DeserializeObject<MyEntity>(JsonConvert.SerializeObject(dto));
什么是更有效的解决方案?
What would be a more efficient solution?
推荐答案
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; }
}
这篇关于将JObject转换为强类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文