[SOLVED] Filter data from deep json child

Issue

the JSON below is taken from other post. My issue is I know the id and I want to find out where is it located. Eg, I got ID 19006 and I want to get Folder2. How am I going to do this.

{
    "data": {
        "id": 0,
        "name": "",
        "childFolders": [{
            "id": 19002,
            "name": "Locker",
            "childFolders": [{
                "id": 19003,
                "name": "Folder1",
                "childFolders": [],
                "childComponents": [{
                    "id": 19005,
                    "name": "route1",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }]
            }, {
                "id": 19004,
                "name": "Folder2",
                "childFolders": [],
                "childComponents": [{
                    "id": 19008,
                    "name": "comm1",
                    "state": "STOPPED",
                    "type": "COMMUNICATION_POINT"
                }, {
                    "id": 19006,
                    "name": "route2",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }, {
                    "id": 19007,
                    "name": "route3",
                    "state": "STOPPED",
                    "type": "ROUTE"
                }]
            }],
            "childComponents": []
        }],
        "childComponents": []
    },
    "error": null
}

Solution

I write code now it is like this:

         var json = GetJsonString();
        
        var model = GetJsonModel(json);

         var folderName = GetName(model.data, 19006); 

I chekced and code is correct. folderName is Folder2

enter image description here

And the recursive code:

 private string GetName(Data data, int searchValue)
    {
        var folderName = data.name;

        foreach (var item in data.childComponents)
        {
            if (item.id == searchValue)
            {
                return folderName;
            }
        }

        if (data.childFolders.Length > 0)
        {
            foreach (var item in data.childFolders)
            {
                var folderName1 = GetName(item, searchValue);

                if (folderName1 != null)
                {
                    return folderName1;
                }
            }
        }

        return null;
    }

Your model is like this:

enter image description here

EDIT:

I parse Json like this.

return JsonSerializer.Deserialize<YourJson>(test);

Answered By – blogprogramisty.net

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *