C# — Load a TreeView from JSON, Save a TreeView to JSON

Here are a few snippets of code I needed for internal tools…

TreeView –> JSON

private void recurseTree(TreeNode treeNode, Chilkat.JsonObject json)
    {
    string tag;
    if (treeNode.Tag == null)
        {
        tag = treeNode.Name;
        }
    else
        {
        tag = treeNode.Tag.ToString();
        if (tag.Length == 0)
            {
            tag = treeNode.Name;
            }
        }

    int numChildren = treeNode.Nodes.Count;
    if (numChildren == 0)
        {
        json.AppendString(tag, treeNode.Text);
        return;
        }

    Chilkat.JsonObject jObj = json.AppendObject(tag);

    foreach (TreeNode tn in treeNode.Nodes)
        {
        recurseTree(tn,jObj);
        }
    }

private void btnTreeViewToJson_Click(object sender, EventArgs e)
    {
    // Convert treeview1 to JSON.
    Chilkat.JsonObject json = new Chilkat.JsonObject();

    TreeNodeCollection nodes = treeView1.Nodes;
    foreach (TreeNode n in nodes)
        {
        recurseTree(n,json);
        }

    json.EmitCompact = false;
    textBox1.Text = json.Emit();
    }

JSON –> TreeView

void buildTreeView(TreeNode node, Chilkat.JsonObject json)
    {
    int i;
    int n = json.Size;
    for (i = 0; i < n; i++)
        {
        if (json.TypeAt(i) == 3)
            {
            TreeNode tn = new TreeNode();
            
            tn.Tag = json.NameAt(i);
            tn.Name = json.NameAt(i);
            tn.Text = json.NameAt(i);
            node.Nodes.Add(tn);

            Chilkat.JsonObject jObj = json.ObjectAt(i);
            buildTreeView(tn, jObj);
            }
        else
            {
            // This is a string.
            TreeNode tn = new TreeNode();
            tn.Tag = json.NameAt(i);
            tn.Name = json.NameAt(i);
            tn.Text = json.StringAt(i);
            node.Nodes.Add(tn);
            }
        }
    }

private void loadTreeView()
    {
    treeView1.BeginUpdate();

    Chilkat.JsonObject json = new Chilkat.JsonObject();

    json.LoadFile("c:/ck2000/appData/builder/treeView.json");

    // recursively add the JSON nodes to the treeview.
    TreeNode tn = new TreeNode();
    tn.Tag = json.NameAt(0);
    tn.Name = json.NameAt(0);
    tn.Text = json.NameAt(0);
    treeView1.Nodes.Add(tn);

    Chilkat.JsonObject jObj = json.ObjectAt(0);
    buildTreeView(tn, jObj);

    treeView1.EndUpdate();
    }

treeView1.Nodes.Clear();
loadTreeView();
...