在C#中使用嵌套数组反序列化JSON

我在这里尝试反序列化这个JSON时遇到了麻烦:

{ "response": { "numfound": 1, "start": 0, "docs": [ { "enID": "9999", "startDate": "2013-09-25", "bName": "XXX", "pName": "YYY", "UName": [ "ZZZ" ], "agent": [ "BobVilla" ] } ] } } 

我为此创建的类是:

 public class ResponseRoot { public Response response; } public class Response { public int numfound { get; set; } public int start { get; set; } public Docs[] docs; } public class Docs { public string enID { get; set; } public string startDate { get; set; } public string bName { get; set; } public string pName { get; set; } public UName[] UName; public Agent[] agent; } public class UName { public string uText { get; set; } } public class Agent { public string aText { get; set; } } 

但是,每当我打电话:

  ResponseRoot jsonResponse = sr.Deserialize(jsonString); 

jsonResponse最终为null,而JSON未反序列化。 我似乎无法说出为什么我的类可能对这个JSON有误。

你的代码表明DocsUName属性是一个对象数组,但它是json中的一个字符串数组,同样适用于agent

试试这个:

  public class Docs { public string enID { get; set; } public string startDate { get; set; } public string bName { get; set; } public string pName { get; set; } public string[] UName; public string[] agent; } 

并删除UNameAgent

这应该适用于您的类,使用json2csharp

 public class Doc { public string enID { get; set; } public string startDate { get; set; } public string bName { get; set; } public string pName { get; set; } public List UName { get; set; } public List agent { get; set; } } public class Response { public int numfound { get; set; } public int start { get; set; } public List docs { get; set; } } public class ResponseRoot { public Response response { get; set; } }