public String GetAllPermissions() { var permissions = PermissionManager.GetAllPermissions();Newtonsoft.Json.JsonConvert.SerializeObject(permissions.ToList()); var st = GenerateMenu(permissions); return st ; }
/// <summary> /// 生成菜单拼接字符串 /// </summary> /// <returns></returns> private string GenerateMenu(IReadOnlyList<Permission> lstAll) { StringBuilder sb = new StringBuilder(); //var lstAll = GetData(); var lstParent = lstAll.ToList().FindAll(x => x.Parent == null).ToList(); var lstChilds = lstAll.ToList().FindAll(x => x.Parent != null).ToList(); if (lstParent.Any()) { sb.Append("["); foreach (var top in lstParent) { var lstOnes = lstChilds.FindAll(x => x.Parent.Name == top.Name).OrderBy(x => x.Name).ToList(); if (lstOnes.Any()) { if (sb.ToString().Substring(sb.ToString().Length - 1, 1) == "[" || sb.ToString().Substring(sb.ToString().Length - 1, 1) == ",") { sb.Append("{"); } else { sb.Append(",{"); } sb.AppendFormat("\"id\":\"{0}\",\"label\":\"{1}\"", top.Name, top.DisplayName) .Append(",\"children\": ["); GetChild(sb, lstChilds, lstOnes); sb.Append("]}"); } else { if (sb.ToString().Substring(sb.ToString().Length - 1, 1) != "[" && sb.ToString().Substring(sb.ToString().Length - 1, 1) != ","&& sb.ToString()!="") { sb.Append(","); } sb.Append("{\"id\":\"" + top.Name + "\",\"label\":\""+ top.DisplayName + "\",\"children\":[]}"); } } sb.Append("]"); } return sb.ToString(); } /// <summary> /// 得到子菜单项 /// </summary> /// <param name="sb">StrignBuilder对象</param> /// <param name="lstChilds">所有子节点集合</param> /// <param name="lstOnes">“父”节点集合</param> private static void GetChild(StringBuilder sb, List<Permission> lstChilds, List<Permission> lstOnes) { foreach (var chld in lstOnes) { var lstTwos = lstChilds.FindAll(x => x.Parent.Name == chld.Name).OrderBy(x => x.Name).ToList(); if (lstTwos.Any()) { if (sb.ToString().Substring(sb.ToString().Length - 1, 1) == "[" || sb.ToString().Substring(sb.ToString().Length - 1, 1) == ",") { sb.Append("{"); } else { sb.Append(",{"); } sb.AppendFormat("\"id\":\"{0}\",\"label\":\"{1}\"", chld.Name, chld.DisplayName) .Append(",\"children\": ["); GetChild(sb, lstChilds, lstTwos); sb.Append("]}"); } else { if (sb.ToString().Substring(sb.ToString().Length - 1, 1) != "[" && sb.ToString().Substring(sb.ToString().Length - 1, 1) != "," && sb.ToString() != "") { sb.Append(","); } sb.Append("{\"id\":\"" + chld.Name + "\",\"label\":\"" + chld.DisplayName + "\",\"children\":[]}"); } } }