简体   繁体   English

JObject JSON 解析嵌套对象

[英]JObject JSON Parsing Nested Object

I'm trying to parse JSON into an array that is formatted like the following:我正在尝试将 JSON 解析为格式如下的数组:

{
    "company": [
        [
            {
                "id": 1,
                "name": "Test Company1"
            },
           {
                "id": 2,
                "name": "Test Company2"
            }
        ]
    ]
}

I'm using Newtonsoft JObjects to do this.我正在使用 Newtonsoft JObjects 来做到这一点。 I have the following code so far, which gets me to the "company" object:到目前为止,我有以下代码,它使我进入“公司”对象:

JObject joResponse = JObject.Parse(json);
JArray arr = (JArray)joResponse["company"];

But there is only one value in the array, it's one single value with the all of the JSON nodes in it:但是数组中只有一个值,它是一个包含所有 JSON 节点的值:

    [
        {
            "id": 1,
            "name": "Test Company1"
        },
       {
            "id": 2,
            "name": "Test Company2"
        }
    ]

So essentially I need to get to that 2nd level, but the 2nd level inside of "company" isn't named so I'm not sure how to access it.所以基本上我需要到达第二级,但是“公司”内部的第二级没有命名,所以我不确定如何访问它。

You can use something like this:你可以使用这样的东西:

JToken arr = joResponse["company"]?.Children().First()[1];

Or:要么:

JToken arr = joResponse["company"]?[0]?[1];

The easiest way to do this is to create classes to hold each object type.最简单的方法是创建类来保存每个对象类型。 This is made more complex by the fact that company is actually an array of arrays, for some reason.由于某种原因, company实际上是一个数组数组,这使得这变得更加复杂。

class Root
{
    public List<List<Company>> companies { get; set; }
}

class Company
{
    public int id { get; set; }
    public string name { get; set; }
}

Then you simply deserialize into the root object然后您只需反序列化为根对象

var result = JsonConvert.DeserializeObject<Root>(json);

var companies = result.companies.SelectMany(c => c).ToList();

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

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