C # Extract JSON from nested array

I am trying to iterate through nested JSON arrays using C # and JSON.NET. JSON represents categories for an online store - below is an example. My goal is to create a list of all category names.

{
  "id": 2,
  "parent_id": 1,
  "name": "Main Category List",
  "is_active": true,
  "position": 1,
  "level": 1,
  "product_count": 0,
  "children_data": [
    {
      "id": 9,
      "parent_id": 2,
      "name": "Mens Clothing",
      "is_active": true,
      "position": 6,
      "level": 2,
      "product_count": 0,
      "children_data": []
    },
    {
      "id": 8,
      "parent_id": 2,
      "name": "Womens Clothing",
      "is_active": true,
      "position": 7,
      "level": 2,
      "product_count": 0,
      "children_data": [
        {
          "id": 223,
          "parent_id": 8,
          "name": "Outdoor Clothing",
          "is_active": true,
          "position": 1,
          "level": 3,
          "product_count": 0,
          "children_data": []
        },
        {
          "id": 224,
          "parent_id": 8,
          "name": "Hiking Clothing",
          "is_active": true,
          "position": 2,
          "level": 3,
          "product_count": 0,
          "children_data": []
        },
        {
          "id": 596,
          "parent_id": 8,
          "name": "Dresses",
          "is_active": true,
          "position": 3,
          "level": 3,
          "product_count": 0,
          "children_data": [
            {
              "id": 694,
              "parent_id": 596,
              "name": "Summer Dresses",
              "is_active": true,
              "position": 13,
              "level": 4,
              "product_count": 0,
              "children_data": [
                {
                  "id": 720,
                  "parent_id": 694,
                  "name": "Accessories",
                  "is_active": true,
                  "position": 1,
                  "level": 5,
                  "product_count": 0,
                  "children_data": [ ]
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id": 10,
      "parent_id": 2,
      "name": "Sale & Clearance",
      "is_active": true,
      "position": 8,
      "level": 2,
      "product_count": 0,
      "children_data": []
    }
  ]
}

      

There may be different levels of categories here, and I need to parse everything. I want to get each category and create a map. For example (Main list of categories → Clothes for women → Outdoor clothing). I think I can check the depth of the children data, but I don't know how to go deeper and deeper into the next Json object.

JObject responseObject = JObject.Parse(response.Content);


foreach (JObject category in getCatResponseObj.SelectToken("children_data"))
{
    while loop checking depth of children_data



}

      

+3


source to share


2 answers


This appears to be a recursively defined structure. You must create a function to extract the values ​​of each of the children so that you can reuse it recursively.

IEnumerable<string> GetCategoryNames(JObject data)
{
    yield return (string)data["name"];
    foreach (var name in data["children_data"].Cast<JObject>().SelectMany(GetCategoryNames))
        yield return name;
}

      

Then call it on the root object so that your names fit into a list or whatever.



var obj = JObject.Parse(response.Content);
var names = GetCategoryNames(obj).ToList();

      

Otherwise, if you want to indiscriminately get all the names in the object tree, just keep in mind that SelectToken()

/ SelectTokens()

also accepts json path requests. Thus, to get all the names of all descendants, you simply do the following:

let names = obj.SelectTokens("..name").ToList();

      

0


source


If it were me, I would create the most complete JSON file I could think of (including all possible entries) and then use json2csharp or an equivalent tool to create C # classes, then deserialize the Json and work with it natively. You may have to massage the results a little - but I think you can get there. If that didn't work, I would use the Newtonsofts JSON LINQ functions (documentation) . JToken gives you parent / child combinations that allow you to navigate up and down the tree. The samples in the documentation are really good, so I don't have to fill the page with duplicate information.

(Created from your example)



public class ChildrenData
{
    public int id { get; set; }
    public int parent_id { get; set; }
    public string name { get; set; }
    public bool is_active { get; set; }
    public int position { get; set; }
    public int level { get; set; }
    public int product_count { get; set; }
    public List<object> children_data { get; set; }
}

public class RootObject
{
    public int id { get; set; }
    public int parent_id { get; set; }
    public string name { get; set; }
    public bool is_active { get; set; }
    public int position { get; set; }
    public int level { get; set; }
    public int product_count { get; set; }
    public List<ChildrenData> children_data { get; set; }
}

      

0


source







All Articles