1

我需要从 Active Directory OU创建一个有效的jqTree JSON 结构。我正在使用递归方法(InfoNode)对此进行测试,但我无法得到它。

生成的 json 进入字符串 json。要处理的第一个节点是具有默认域根的 DirectoryEntry 父节点。递归方法 (InfoNode) 获取当前子节点,按“OU”过滤并创建 JSON 属性“标签”和“路径”。之前检查此节点是否有更多子节点来写入当前 JSON 项的末尾。最后,如果有更多的孩子,再次运行方法(InfoNode):

public static DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
public string dom = (string)root.Properties["defaultNamingContext"].Value;

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

void InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');

    if (arr[0] == "OU")
    {
        json += "'children':[{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (nodo.Children == null)
        {
            json += "}]";
        }
        else
        {
            json += ",";
        }              
    }

    if (node.Children != null)
    {
        foreach (DirectoryEntry child in node.Children)
        {
            InfoNode(child);
        }
    }
}
4

1 回答 1

0

您应该提供有关代码失败的更多详细信息。

我会试一试:-)

您可以尝试修改您的代码,如下所示。不是最佳的(在拆分之前使用startswith,更多的string.Format,在递归调用该方法之前使用startswith测试孩子会更好),但我想它应该可以工作。

当您在树中进行时,您可能需要从 ldap 源加载子项。

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    json = InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

public string InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');
    var result = string.Empty;

    if (arr[0].Equals("ou",StringComparison.InvariantCultureIgnoreCase))
    {
        result = "'{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (node.Children.Cast<DirectoryEntry>().Any())
        {
            result += String.Format(", children:[{0}]",
                                    String.Join(",\n ",
                                                node.Children.Cast<DirectoryEntry>()
                                                    .Select(InfoNode).Where(s=>!string.IsNullOrEmpty(s))
                                                    .ToArray()));
        }
        result += "}";
    }
    return result;
}
于 2012-12-04T13:12:31.113 回答