I'm not going to post full working code here since the code I have written for this scenario was done for a client. What I am going to post is a general outline for how you can achieve saving/restoring the TreeNodes in a WinForms TreeView using JSON.
A. you start off with a simple class to model a TreeNode:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;
[DataContract]
public class TNode
{
[DataMember]
public TNode Parent { set; get; }
[DataMember]
public string Text { set; get; }
[DataMember]
public string Tag { set; get; }
[DataMember]
public bool CState { set; get; }
public TNode(TNode parent, string txt, bool cstate, string tag)
{
Parent = parent;
Text = txt;
CState = cstate;
Tag = tag;
}
}
You'll note that the node "model" here has no list of child-nodes: that's by design, and "resurrecting" the correct parent-child relationships is dependent on a certain use of recursion.
B. Then, a Class that will hold the collection of TreeNode "models:"
[DataContract]
public class TNodeCollection
{
[DataMember]
public List<TNode> NodeCollection { set; get; }
public TNodeCollection(TreeNodeCollection nodes)
{
NodeCollection = new List<TNode>();
ParseTree(null, nodes);
}
}
Once you have this "flat list" of TNodes created, it is a simple matter to save that as JSON, and to read it back in, from JSON.
The interesting part is how you recreate from the de-serialized flat list the correct parent-child node relationships. That is achieved by using the fact the node models are created by using depth-first recursion when parsing the TreeView TreeNodeCollection: since Parent Nodes will have been created
before their child-nodes, we can use the TreeNodeCollection.Find("nodename", true) method to locate the Parent node as we read the child node, and, then, set the child Node's Parent.
Your code in the Form where you want to save/serialize the TreeView might look like this:
TNodeCollection coll = new TNodeCollection(treeView1.Nodes);
coll.SaveJSON();
coll.RestoreJSON(treeView1);