ObjectTreeNode.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Web.Script.Serialization;
  4. namespace MECF.Framework.UI.Core.ExtendedControls
  5. {
  6. public class ObjectTreeNode
  7. {
  8. public string Name { get; set; }
  9. public string Value { get; set; }
  10. public List<ObjectTreeNode> Children { get; set; } = new List<ObjectTreeNode>();
  11. public static ObjectTreeNode CreateTree(object obj)
  12. {
  13. JavaScriptSerializer jss = new JavaScriptSerializer();
  14. var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  15. Dictionary<string, object> dic = jss.Deserialize<Dictionary<string, object>>(serialized);
  16. var root = new ObjectTreeNode();
  17. root.Name = "Root";
  18. BuildTree(dic, root);
  19. return root;
  20. }
  21. private static void BuildTree(object item, ObjectTreeNode node)
  22. {
  23. if (item is KeyValuePair<string, object>)
  24. {
  25. KeyValuePair<string, object> kv = (KeyValuePair<string, object>) item;
  26. ObjectTreeNode keyValueNode = new ObjectTreeNode();
  27. keyValueNode.Name = kv.Key;
  28. keyValueNode.Value = GetValueAsString(kv.Value);
  29. node.Children.Add(keyValueNode);
  30. BuildTree(kv.Value, keyValueNode);
  31. }
  32. else if (item is ArrayList)
  33. {
  34. ArrayList list = (ArrayList) item;
  35. int index = 0;
  36. foreach (object value in list)
  37. {
  38. ObjectTreeNode arrayItem = new ObjectTreeNode();
  39. arrayItem.Name = $"[{index}]";
  40. arrayItem.Value = "";
  41. node.Children.Add(arrayItem);
  42. BuildTree(value, arrayItem);
  43. index++;
  44. }
  45. }
  46. else if (item is Dictionary<string, object>)
  47. {
  48. Dictionary<string, object> dictionary = (Dictionary<string, object>) item;
  49. foreach (KeyValuePair<string, object> d in dictionary)
  50. {
  51. BuildTree(d, node);
  52. }
  53. }
  54. }
  55. private static string GetValueAsString(object value)
  56. {
  57. if (value == null)
  58. return "null";
  59. var type = value.GetType();
  60. if (type.IsArray)
  61. {
  62. return "[]";
  63. }
  64. if (value is ArrayList)
  65. {
  66. var arr = value as ArrayList;
  67. return $"[{arr.Count}]";
  68. }
  69. if (type.IsGenericType)
  70. {
  71. return "{}";
  72. }
  73. return value.ToString();
  74. }
  75. }
  76. }