问题
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; }
}
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?
回答1:
Add TypeNameHandling
private readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto
};
Here's example
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; }
}
来源:https://stackoverflow.com/questions/20847052/convert-a-jobject-to-a-strongly-typed-object