我一直在尝试使用JSON.Net反序列化C#中的JSON流

我有一个JObject'JO1',当我对该字符串内容执行JO1.ToString()时:

{
  "Successful": true,
  "Value": [
    {
      "no": "1",
      "name": "Accounting"
    },
    {
      "no": "2",
      "name": "Marketing"
    },
    {
      "no": "3",
      "name": "Information Technology"
    }
  ]
}


我尝试以下.NET代码无济于事。

public class main()
{
  public void main()
  {
   JObject jo = new JObject();
   jo = functionthatretrievestheJSONdata();

   List<departments> dt1 = JsonConvert.DeserializeObject<List<departments>>(jo.ToString());
  }
}

public class departments
{
    public int no { get; set; }
    public string name { get; set; }
}


有人可以给我正确的方向指示吗?

最佳答案

您将需要一个包装List<departments>的类,如下所示:

public class DeserializedDepartments
{
    public bool Successful { get; set; }
    public List<departments> Value { get; set; }
}


所以您会像这样反序列化:

DeserializedDepartments dt1 =
    JsonConvert.DeserializeObject<DeserializedDepartments>(jo.ToString());


现在,您的List<departments>位于Valuedt1中;或dt1.Value

09-26 04:00