将JObject转换为强类型对象

时间:2013-12-30 20:31:23

标签: .net json json.net

我正在使用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));

什么是更有效的解决方案?

1 个答案:

答案 0 :(得分:3)

添加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; }
}