I have to convert a TreeView
object to JSON using C#. I am currently using JsonConvert.SerializeObject()
.
public class SubTreeNode : TreeNode
{
public CustomProperties customProperties;
}
public class CustomProperties
{
public string property1 = "Property1";
public string property2 = "Property2";
public string property3 = "Property3";
}
When tried it with JsonConvert.SerializeObject(treeView1.Nodes);
it only returned the top nodes... not the child nodes, sub-child, and so on.
What is the easiest way to serialize and deserialize this TreeView object?
using custom json serializer worked for me
This is my solution:
First I create a node class that contains the data structure I want for the nodes, and a JSon method that serialize the object
I wrote a method that it's meant to be called recursively. This returns a list of the children nodes given a particular tree node
I wrote and update object method to create a root node where I can contain all the nodes of the treeview. I decided to use a root node instead of a list of nodes, because a list wouldn't have the JSon method that serialize the object.
The root object must be declared as a single node
and you can just call the JSon method of root
I hope this helps
You will need to add methods that produce JSON from each node recursively.
Check out the related post: Serializing a Tree into Json Object.
I was confronted with the same problem: only top nodes are exported with the standard JSON.Net Serializer because, as fero under the above link rightly states, "your TreeNode class is serialized as an array because it implements IEnumerable". It further says you should decorate the TreeNode class with the JsonConverterAttribute. I didn't get this to work.
Here is an alternative. Please note that this may not be seen as the best way to do it. But it is pretty simple:
Create a new hierarchical class with the information you want to export in JSON (in my case, I only want to export part of my treenode-properties, so creating a new simple class made sense twice):
Recursively move your data from TreeView to a new JTree (our custom class):
Write simplified JSON tree to file using JSON.NET Serializer:
Final txt (example):