问题
I'm having trouble trying to deserialize this JSON here:
{
"response": {
"numfound": 1,
"start": 0,
"docs": [
{
"enID": "9999",
"startDate": "2013-09-25",
"bName": "XXX",
"pName": "YYY",
"UName": [
"ZZZ"
],
"agent": [
"BobVilla"
]
}
]
}
}
The classes I created for this are:
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; }
}
But, whenever I call:
ResponseRoot jsonResponse = sr.Deserialize<ResponseRoot>(jsonString);
jsonResponse ends up being null and the JSON isn't deserialized. I can't seem to tell why my classes may be wrong for this JSON.
回答1:
your code suggest that the UName Property of Docs is an array of objects, but it's an array of strings in json, same goes for agent
try this:
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;
}
and remove the UName and Agent classes
回答2:
This should work for your classes, using 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<string> UName { get; set; }
public List<string> agent { get; set; }
}
public class Response
{
public int numfound { get; set; }
public int start { get; set; }
public List<Doc> docs { get; set; }
}
public class ResponseRoot
{
public Response response { get; set; }
}
来源:https://stackoverflow.com/questions/20133280/deserializing-json-with-nested-arrays-in-c-sharp