C#中处理嵌套数组的JSON反序列化

8

我在尝试反序列化这个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<ResponseRoot>(jsonString);

jsonResponse 最终变成了 null,JSON 没有被反序列化。我似乎无法确定我的类在这个 JSON 中可能是错误的原因。


此外,我还遇到了这个错误:无法将类型为“System.String”的对象转换为类型“UName”。 - jymbo
2
DocsUNameagent 成员不应该是字符串数组吗? - Asad Saeeduddin
uname和agent在示例JSON中看起来像字符串列表。 - Reacher Gilt
4
你试过 http://json2csharp.com/ 吗? - L.B
json2csharp.com真的很棒 :) 感谢@L.B - Nav
2个回答

13

使用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; }
}

1
不知道这个网站,谢谢! - jymbo
没问题,这非常方便 ;) - Christian Phillips
1
谢谢您提供的链接,帮了很大的忙。 - Izzy

9

您的代码表明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


1
例如,如果“UName”确实是指定的类,则JSON将具有{uText:“ZZZ”}而不仅仅是“ZZZ” - T.J. Crowder
做到了!!谢谢! - jymbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接