Convert a JObject to a strongly typed object

前提是你 提交于 2019-12-10 19:44:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!