通过代码将几个可用类之一设置为Json DeserializeObject

时间:2013-01-09 05:42:09

标签: c# json windows-phone-7

我有几个课程

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 case,我如何使下面的WHICHLASS表示正确的类?像

这样的东西
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);

1 个答案:

答案 0 :(得分:0)

我认为创建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 );