1

Firstly, I read heaps of topics about JSON to TreeView on the Stackoverflow. After this, I create a JSON data like this:

{
    "Cars": {
            "Audi": [{
                "A6 2.0 TDI quatro 2018 Red": ["S-Line", "17 inch rim", "Full sport packet"],
                "A5 1.6 TFSI 2018 Blue": ["Desing packet", "Sunroof"]
            }],
            "Mercedes-Benz": [{
                "E220d AMG 2018 white": ["Glass ceiling", "Vacuum doors", "Navigation"],
                "E220d Exclusive Black 2018 Blue": ["Power seats", "Start & Stop"]
            }]
        }
}

Here is the C# code content:

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        treeView1.Nodes.Clear();
        var json = File.ReadAllText(Uz.path + @"cars.json");
        var obj = JObject.Parse(json);
        var parent = Json2Tree(obj);
        treeView1.Nodes.Add(parent);
        treeView1.ExpandAll();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, @"ERROR");
    }
}
private static TreeNode Json2Tree(JObject obj)
{
    //create the parent node
    var parent = new TreeNode();
    //loop through the obj. all token should be pair<key, value>
    foreach (var token in obj)
    {
        //change the display Content of the parent
        parent.Text = token.Key;
        //create the child node
        var child = new TreeNode();
        child.Text = token.Key;
        //check if the value is of type obj recall the method
        if (token.Value.Type.ToString() == "Object")
        {
            // child.Text = token.Key.ToString();
            //create a new JObject using the the Token.value
            var o = (JObject)token.Value;
            //recall the method
            child = Json2Tree(o);
            //add the child to the parentNode
            parent.Nodes.Add(child);
        }
        //if type is of array
        else if (token.Value.Type.ToString() == "Array")
        {
            int ix = -1;
            //  child.Text = token.Key.ToString();
            //loop though the array
            foreach (var itm in token.Value)
            {
                //check if value is an Array of objects
                if (itm.Type.ToString() == "Object")
                {
                    //child.Text = token.Key.ToString();
                    //call back the method
                    ix++;

                    var o = (JObject)itm;
                    var objTN = Json2Tree(o);
                    //objTN.Text = token.Key + "[" + ix + "]";
                    child.Nodes.Add(objTN);
                    //parent.Nodes.Add(child);
                }
                //regular array string, int, etc
                else if (itm.Type.ToString() == "Array")
                {
                    ix++;
                    var dataArray = new TreeNode();
                    foreach (var data in itm)
                    {
                        //dataArray.Text = token.Key + "[" + ix + "]";
                        dataArray.Nodes.Add(data.ToString());
                    }
                    child.Nodes.Add(dataArray);
                }
                else
                {
                    child.Nodes.Add(itm.ToString());
                }
            }
            parent.Nodes.Add(child);
        }
        else
        {
            //if token.Value is not nested
            // child.Text = token.Key.ToString();
            //change the value into N/A if value == null or an empty string 
            child.Nodes.Add(token.Value.ToString() == "" ? "N/A" : token.Value.ToString());
            parent.Nodes.Add(child);
        }
    }
    return parent;
}

when I run the code, the screenshot looks like this:

enter image description here

But marked as 1, 2 and 3 are should not be shown. It must be like this: enter image description here

Although I worked 3 days, I did not succeed.

3
  • Do you have to use that JSON structure? I think you are overcomplating yourself way too much here Commented May 23, 2018 at 10:27
  • 1
    It seems that code you are using to generate TreeNodeCollection is not correct. You can check this link github.com/huseyint/JsonTreeView which does the same what you are indented for. Commented May 23, 2018 at 10:29
  • Have you tried the code from How to recursively populate a TreeView with JSON data? Commented May 23, 2018 at 16:59

1 Answer 1

1

In JsonTreeView project, it show like this:

using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace JsonTreeView
{
    public static class JsonToTreeView
    {
        public static void Json2Tree(this TreeView treeView, string json, string group_name)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return;
            }
            var obj = JObject.Parse(json);
            AddObjectNodes(obj, group_name, treeView.Nodes);
        }

        public static void AddObjectNodes(JObject obj, string name, TreeNodeCollection parent)
        {
            var node = new TreeNode(name);
            parent.Add(node);

            foreach (var property in obj.Properties())
            {
                AddTokenNodes(property.Value, property.Name, node.Nodes);
            }
        }

        private static void AddArrayNodes(JArray array, string name, TreeNodeCollection parent)
        {
            var node = new TreeNode(name);
            parent.Add(node);

            for (var i = 0; i < array.Count; i++)
            {
                AddTokenNodes(array[i], $"[{i}]", node.Nodes);
            }
        }

        private static void AddTokenNodes(JToken token, string name, TreeNodeCollection parent)
        {
            switch (token)
            {
                case JValue _:
                    parent.Add(new TreeNode($"{((JValue) token).Value}"));
                    break;
                case JArray _:
                    AddArrayNodes((JArray)token, name, parent);
                    break;
                case JObject _:
                    AddObjectNodes((JObject)token, name, parent);
                    break;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.