繁体   English   中英

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

[英]Deserializing JSON with nested arrays in C#

我在这里尝试反序列化这个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有误。

你的代码表明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<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; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM