Search code examples
c#jsonwpftreeview

How to convert from WPF TreeView to JSON


I have the following JSON structure

{
    "test1.1": {
        "test2.2": {},
        "test2.3": {},
        "test2.4": {
            "test3.1": {},
            "test3.2": {},
            "test3.3": {}
        },
        "test2.5": {
            "test4.1": {},
            "test4.2": {},
            "test4.3": {}
        }
    }
}

and I'm able to display it in a TreeView in WPF:

enter image description here

now I want to convert the TreeView back into the same JSON structure/file.

This is my approach so far but having trouble getting to the exact same

    private string ConvertTreeViewToJson(TreeView treeView)
    {
        List<object> treeViewItems = new List<object>();
        foreach (TreeViewItem item in treeView.Items)
        {
            treeViewItems.Add(Recursion(item));
        }

        return JsonConvert.SerializeObject(treeViewItems, Formatting.Indented);
    }

    private object Recursion(TreeViewItem item)
    {
        var node = new List<object>() {item.Header};

        if (item.HasItems)
        {
            List<object> children = new List<object>();
            foreach (TreeViewItem childItem in item.Items)
            {
                children.Add(Recursion(childItem));
            }
            node.Add(children);
        }

        return node;
    }

this is the return:

[["test1.1",[["test2.2"],["test2.3"],["test2.4",[["test3.1"],["test3.2"],["test3.3"]]],["test2.5",[["test4.1"],["test4.2"],["test4.3"]]]]]]

Solution

  • Inspired by the answer I originally linked under your question in a comment, I figured out a solution. In order for JsonConvert to return key-value pairs instead of arrays, you should use a Dictionary<string,object> instead of a List<object>.

    The Key string of each entry will store the header value of a TreeViewItem, and the Value of that same entry will store a nested Dictionary with all the corresponding TreeViewItems:

    private string ConvertTreeViewToJson(TreeView treeView)
    {
        var treeViewItems = new Dictionary<object,object>();
    
        foreach (TreeViewItem item in treeView.Items)
        {
            treeViewItems.Add(item.Header.ToString(), Recursion(item));
        }
    
        return JsonConvert.SerializeObject(treeViewItems, Newtonsoft.Json.Formatting.Indented);
    }
    
    private Dictionary<string, object> Recursion(TreeViewItem item)
    {
        if (item.HasItems)
        {
            var children = new Dictionary<string,object>();
    
            foreach (TreeViewItem childItem in item.Items)
            {
                var grandChildren = Recursion(childItem);
    
                children.Add(childItem.Header.ToString(), grandChildren);
            }
            return children;
        }
    
        return new Dictionary<string, object>();
    }