具有动态类型:
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.components
是JToken
,则使用JToken.ToObject(Type)
:将更有效
var components = (IList)include.components.ToObject(typeof(List<>).MakeGenericType(new[] { targetType }));