JSON.NET反序列化为运行时类型列表

时间:2016-03-24 11:47:47

标签: c# .net json serialization json.net

拥有动态类型:

Type targetType;
if (position.Length == 1)
{
    targetType = typeof (Row);
}

if (position.Length == 4)
{
    targetType = typeof (Field);
}

在此之后,我需要将JSON反序列化为此类型的List:

List<targetType>

代码:

var components = JsonConvert.DeserializeObject<List<targetType>>(include.components.ToString());

我是如何做到的?

1 个答案:

答案 0 :(得分:0)

您可以将JsonConvert.DeserializeObject(String, Type)Type.MakeGenericType(Type[])一起使用:

var components = (IList)JsonConvert.DeserializeObject(include.components.ToString(), typeof(List<>).MakeGenericType(new[] { targetType }));

顺便提一下,如果include.componentsJToken,那么使用JToken.ToObject(Type)会更有效:

var components = (IList)include.components.ToObject(typeof(List<>).MakeGenericType(new[] { targetType }));