How to recursively parse json and find a specific object?

Viewed 104

This is my JSON file click me !

Following,C# classes from JSON

public class SiteNode
{
    public string url;
    public string[] param;
    public string serviceid;
    public bool is_enabled;
    public string icon;
    public string nodetype;
    public string api;
    public NodeMeta meta;
    public class NodeMeta
    {
        public bool is_module_legal;
        public string module;
        public string func;
        public MuiText title;
        public MuiText desc;
        public string group;
        public List<string> granted_roles;
    }
    public class MuiText
    {
        public string tw;
        public string gb;
        public string en;
    }
    public List<SiteNode> children;
}

I have already use the JavaScriptSerializer.Deserialize method to convert to List ,But I have no idea to find serviceid==System-016 this object.

Special attention to the object in Json file can be changed location,So I think to use recursive to process this problem.

Please, provide me a solution,Thanks a lot!

2 Answers

You could use a method that iterates through all nodes in the tree, for example:

public static IEnumerable<T> Flatten<T>(T node, Func<T, IEnumerable<T>> childSelector)
{
    yield return node;

    var children = childSelector(node);

    if (children == null)
    {
        yield break;
    }

    foreach (var child in children)
    {
        foreach (var grandChild in Flatten(child, childSelector))
        {
            yield return grandChild;
        }
    }
}

Then use it to flatten out your tree structure before filtering the whole set or finding a specific node, for example:

var rootNode = JavaScriptSerializer.Deserialize<SiteNode>(json);
var filteredNodes = Flatten(rootNode, n => n.children)
    .Where(n => n.serviceid== "System-016");

If I understand you correctly, you would like to query the object from the list? After you have deseriliazed from Json.

var yourObject = SiteNode.Where(s => s.serviceId == "System-16").firstOrDefault()
Related