简体   繁体   English

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

[英]Deserializing JSON with nested arrays in C#

I'm having trouble trying to deserialize this JSON here: 我在这里尝试反序列化这个JSON时遇到了麻烦:

{
    "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. jsonResponse最终为null,JSON没有反序列化。 I can't seem to tell why my classes may be wrong for this JSON. 我似乎无法说出为什么我的类可能对这个JSON有误。

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 你的代码表明DocsUName属性是一个对象数组,但它是json中的一个字符串数组,同样适用于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 并删除UNameAgent

This should work for your classes, using json2csharp 这应该适用于您的类,使用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