【问题标题】:Deserializing JSON with nested arrays in C#在 C# 中使用嵌套数组反序列化 JSON
【发布时间】:2013-11-21 22:28:19
【问题描述】:

我在这里尝试反序列化此 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”类型
  • Docs 上的 UNameagent 成员不应该是字符串数组吗?
  • uname 和 agent 看起来像示例 json 中的字符串列表。
  • 你试过json2csharp.com吗?
  • json2csharp.com 真的是 g8 :) 谢谢@L.B

标签: c# json deserialization


【解决方案1】:

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

【讨论】:

  • 例如,如果 UName 确实是指定的类,则 JSON 将具有 {uText: "ZZZ"} 而不仅仅是 "ZZZ"
  • 哇!!做到了。谢谢!
【解决方案2】:

这应该适用于您的课程,使用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; }
}

【讨论】:

  • 不知道这个网站。谢谢!
  • 没问题,很方便;)
  • 谢谢你的链接..帮助了很多
  • 感谢您的链接。它有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多