C# TreeView to JSON and Back
Here’s a C# class for persisting a TreeView to JSON, and for restoring a TreeView from JSON.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ChilkatRelease { public class TreeviewPersist { // Persist the TreeView to a JSON string. static public string ToJson(TreeView treeView) { Chilkat.JsonObject tvJson = new Chilkat.JsonObject(); Chilkat.JsonArray tvNodes = tvJson.AppendArray("treeViewNodes"); TreeNodeCollection nodes = treeView.Nodes; foreach (TreeNode n in nodes) { serializeTree(tvNodes, n); } tvJson.EmitCompact = false; return tvJson.Emit(); } // Clears the passed-in treeView and rebuilds from JSON. static public void FromJson(string strJson, TreeView treeView) { treeView.Nodes.Clear(); Chilkat.JsonObject tvJson = new Chilkat.JsonObject(); tvJson.Load(strJson); Chilkat.JsonArray tvNodes = tvJson.ArrayOf("treeViewNodes"); int numNodes = tvNodes.Size; for (int i = 0; i < numNodes; i++) { Chilkat.JsonObject json = tvNodes.ObjectAt(i); if (json.IsNullOf("parentName")) { TreeNode node = treeView.Nodes.Add(json.StringOf("name"), json.StringOf("text")); restoreNode(node, json); } else { // Assumes unique names (i.e. keys) TreeNode[] foundNodes = treeView.Nodes.Find(json.StringOf("parentName"), true); if (foundNodes.Length > 0) { TreeNode node = foundNodes[0].Nodes.Add(json.StringOf("name"), json.StringOf("text")); restoreNode(node, json); } } } } // Restore the properties of a TreeNode from JSON. static private void restoreNode(TreeNode node, Chilkat.JsonObject json) { node.Tag = json.StringOf("tag"); node.Text = json.StringOf("text"); node.ToolTipText = json.StringOf("toolTipText"); node.Checked = json.BoolOf("checked"); } // Recursive method to add TreeView nodes to the JSON. static private void serializeTree(Chilkat.JsonArray tvNodes, TreeNode treeNode) { tvNodes.AddObjectAt(-1); Chilkat.JsonObject json = tvNodes.ObjectAt(tvNodes.Size-1); json.UpdateString("name", treeNode.Name); TreeNode parent = treeNode.Parent; if (parent != null) { json.UpdateString("parentName", treeNode.Parent.Name); } else { json.UpdateNull("parentName"); } json.UpdateString("tag", (string)treeNode.Tag); json.UpdateString("text", treeNode.Text); json.UpdateString("toolTipText", treeNode.ToolTipText); json.UpdateBool("checked", treeNode.Checked); foreach (TreeNode tn in treeNode.Nodes) { serializeTree(tvNodes,tn); } } } }
admin
0
Tags :