Home > Mobile >  C# How to get from json file list of nodes that contains specific key-value
C# How to get from json file list of nodes that contains specific key-value

Time:09-17

I have a json file like this:

[
    {
        "key1": {
            "find": 5,
            "count": 65,
            "name": "Parser"
        },
        "init": {
            "key2": {
                "find": 5,
                "count": 15,
                "name": "Some"
            },
            "arr": [
                    {
                    "key2": {
                        "find": 8,
                        "count": 32,
                        "name": "Object"
                    },
                    "temp": {
                        "pay": null
                    }
                }
            ]
        }
    },
    {
        "key3": {
            "find": 5,
            "count": 23,
            "name": "String"
        },
        "classes": [],
    }
]

And I want to get list of all nodes that contains key "find" and value "5". The result have to be:

{
    "find": 5,
    "count": 65,
    "name": "Parser"
},
{
    "find": 5,
    "count": 15,
    "name": "Some"
},
{
    "find": 5,
    "count": 23,
    "name": "String"
}

The difficulty is that the nesting can be any, but I need to get only those nodes that contain key "find" and the value "5" for it. How can I go through the entire file and get the nodes I need?

CodePudding user response:

You can do this via recursion. Add new method which check if its type is an object or an array and use it in your main method while there is nodes in json

CodePudding user response:

You can use JToken for this purpose, use the below function to find the nodes.

public void FindNodes(JToken json, string name, string value, List<JToken> nodes)
{
    if (json.Type == JTokenType.Object)
    {
        foreach (JProperty child in json.Children<JProperty>())
        {
            if (child.Name == name && child.Value.ToString() == value)
            {
                nodes.Add(child);
            }
            FindNodes(child.Value, name, value, nodes);
        }
    }
    else if (json.Type == JTokenType.Array)
    {
        foreach (JToken child in json.Children())
        {
            FindNodes(child, name, value, nodes);
        }
    }
}

Use the method in this way,

var json = JsonConvert.DeserializeObject<JToken>(jsonString);
var nodes = new List<JToken>();
FindNodes(json, "find", "5", nodes);
  • Related