如何递归解析json并找到特定对象?

时间:2020-04-04 09:23:27

标签: c# json

这是我的JSON文件click me

遵循JSON中的C#类

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;
}

我已经使用JavaScriptSerializer.Deserialize方法转换为List,但是我不知道找到 serviceid == System-016 该对象。

特别注意可以更改Json文件中的对象的位置,因此我认为可以使用递归来处理此问题。

请给我一个解决方案,非常感谢!

2 个答案:

答案 0 :(得分:3)

您可以使用一种遍历树中所有节点的方法,例如:

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;
        }
    }
}

然后在过滤整个集合或查找特定节点之前,使用它来展平您的树结构,例如:

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

答案 1 :(得分:-3)

如果我对您的理解正确,那么您想从列表中查询对象吗?从Json撤离后。

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