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



具有动态类型:

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

之后,我需要将JSON反序列化为以下类型的列表:

List<targetType>

代码:

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

我是怎么做到的?

您可以将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 }));

相关内容

  • 没有找到相关文章

最新更新