通过代码将几个可用类中的一个设置为Json DeserializeObject
本文关键字:一个 设置 DeserializeObject Json 代码 几个 | 更新日期: 2023-09-27 17:51:01
我有几个类
public class JsonWorldRanking
{
public int no { get; set; }
public string deviceid { get; set; }
public string name { get; set; }
public int clicks { get; set; }
public int country { get; set; }
}
public class JsonNationalRanking
{
public int no { get; set; }
public string deviceid { get; set; }
public string name { get; set; }
public int clicks { get; set; }
}
public class JsonCountryRanking
{
public int no { get; set; }
public int countryIndexRanking { get; set; }
public int clicks { get; set; }
}
我想根据一定的条件选择这三个类中的任何一个进行Json反序列化操作。因此,如果使用开关情况为例,我如何使下面的哪个类代表正确的类?就像
switch value
{
case 0:
WHICHCLASS = JsonWorldRanking;
break;
case 1:
WHICHCLASS = JsonNationalRanking;
break;
case 2:
WHICHCLASS = JsonCountryRanking
break;
}
...
var deserialized = JsonConvert.DeserializeObject<List<WHICHCLASS>>(r.EventArgs.Result);
我认为最好创建t的泛型方法,但这也可以工作
Type destinationType = null;
switch value
{
case 0:
destinationType = typeof(JsonWorldRanking);
break;
case 1:
destinationType = typeof(JsonNationalRanking);
break;
case 2:
destinationType = typeof(JsonCountryRanking);
break;
}
...
Type listType = typeof(List<>);
Type[] typeArgs = {destinationType};
type requiredGenericListType = listType.MakeGenericType(typeArgs);
var deserialized = JsonConvert.Deserialize(r.EventArgs.Result, requiredGenericListType );