Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON with nested arrays in C#

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.

like image 247
jymbo Avatar asked Nov 21 '13 22:11

jymbo


2 Answers

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

like image 91
x4rf41 Avatar answered Sep 19 '22 12:09

x4rf41


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; }
}
like image 31
Christian Phillips Avatar answered Sep 19 '22 12:09

Christian Phillips