簡體   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