Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively populate a TreeView with JSON data

I have a winforms treeview, I can read data automatically, (a node that is equal to key, and a node inside that is equal to value), but when reading object type, the values inside it are not going to be child of object node (key of object), (maybe I couldnt explain well, here is a screenshot and my methods.)

layer0 needs to be inside textures and scale needs to be inside display

layer0 needs to be inside textures and scale needs to be inside display

My Json:

{
"parent": "builtin/generated",
"textures": {
    "layer0": "mm:items/iron_dust"
},
"display": {       
        "scale": [ 1.7, 1.7, 1.7 ]
 }
}

My method to auto detect(not all mine actually)

private void Form1_Load(object sender, EventArgs e)
    {
        StreamReader reader = new StreamReader(path);
        string json = reader.ReadToEnd();
        reader.Close();
        JObject obj = JObject.Parse(json);
        getAllProperties(obj);
    }

    void getAllProperties(JToken children)
    {
        TreeNode mainNode = treeView1.Nodes[0];
        mainNode.Text = Path.GetFileNameWithoutExtension(path);
        foreach (JToken child in children.Children())
        {
            var property = child as JProperty;
            if (property != null)
            {
                if (property.Value.Type == JTokenType.String)
                {
                    TreeNode keyNode = mainNode.Nodes.Add(property.Name);
                    keyNode.Nodes.Add(property.Value.ToString());
                }
                if (property.Value.Type == JTokenType.Array)
                {
                    JArray array = (JArray)property.Value;
                    TreeNode node = mainNode.Nodes.Add(property.Name);
                    for (int i = 0; i < array.Count; i++)
                    {
                        node.Nodes.Add(array[i].ToString());
                    }
                }
                if (property.Value.Type == JTokenType.Object)
                {
                    TreeNode topNode = mainNode.Nodes.Add(property.Name.ToString());
                    foreach (var item in property)
                    {
                        if (item.Type == JTokenType.String)
                        {
                             if (property.Value.Type == JTokenType.String)
                {
                    TreeNode keyNode = topNode.Nodes.Add(property.Name);
                    keyNode.Nodes.Add(property.Value.ToString());
                }
                if (property.Value.Type == JTokenType.Array)
                {
                    JArray array = (JArray)property.Value;
                    TreeNode node = topNode.Nodes.Add(property.Name);
                    for (int i = 0; i < array.Count; i++)
                    {
                        node.Nodes.Add(array[i].ToString());
                    }
                }
                        }
                    }
                }


                    // Console.WriteLine(property.Name + ":" + property.Value);//print all of the values
                }
                getAllProperties(child);
            }
        }

    }

I tried to get parent, but it didnt have name and value properties :S. Any help? (Sorry for language mistakes)

like image 336
Talha Talip Açıkgöz Avatar asked Sep 24 '16 07:09

Talha Talip Açıkgöz


People also ask

How is JSON data stored in snowflakes?

In Snowflake, you can natively ingest semi-structured data not only in JSON but also in XML, Parquet, Avro, ORC, and other formats. This means that in Snowflake, you can efficiently store JSON data and then access it using SQL. Snowflake JSON allows you to load JSON data directly into relational tables.

How do you search in TreeView?

TreeView enables you to search for the nodes matching the specified string. To search for a node in TreeView, you can use Search or SearchAll method of C1TreeView class.


1 Answers

Here is my crack at it. The output is identical to Notepad++'s JSTool plug-in: TreeView showing JSON

The code is structured as a TreeView extension:

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

namespace TestDLApp.Utilities.Extensions
{
    public static class ObjectToTreeView
    {
        private sealed class IndexContainer
        {
            private int _n;
            public int Inc() => _n++;
        }

        private static void FillTreeView(TreeNode node, JToken tok, Stack<IndexContainer> s)
        {
            if (tok.Type == JTokenType.Object)
            {
                TreeNode n = node;
                if(tok.Parent != null)
                {
                    if(tok.Parent.Type == JTokenType.Property)
                    {
                        n = node.Nodes.Add($"{((JProperty)tok.Parent).Name} <{tok.Type.ToString()}>");
                    }
                    else
                    {
                        n = node.Nodes.Add($"[{s.Peek().Inc()}] <{tok.Type.ToString()}>");
                    }
                }
                s.Push(new IndexContainer());
                foreach (var p in tok.Children<JProperty>())
                {
                    FillTreeView(n, p.Value, s);
                }
                s.Pop();
            }
            else if (tok.Type == JTokenType.Array)
            {
                TreeNode n = node;
                if(tok.Parent != null)
                {
                    if (tok.Parent.Type == JTokenType.Property)
                    {
                        n = node.Nodes.Add($"{((JProperty)tok.Parent).Name} <{tok.Type.ToString()}>");
                    }
                    else
                    {
                        n = node.Nodes.Add($"[{s.Peek().Inc()}] <{tok.Type.ToString()}>");
                    }
                }
                s.Push(new IndexContainer());
                foreach (var p in tok)
                {
                    FillTreeView(n, p, s);
                }
                s.Pop();
            }
            else
            {
                var name = string.Empty;
                var value = JsonConvert.SerializeObject(((JValue)tok).Value);

                if (tok.Parent.Type == JTokenType.Property)
                {
                    name = $"{((JProperty)tok.Parent).Name} : {value}";
                }
                else
                {
                    name = $"[{s.Peek().Inc()}] : {value}";
                }

                node.Nodes.Add(name);
            }
        }

        public static void SetObjectAsJson<T>(this TreeView tv, T obj)
        {
            tv.BeginUpdate();
            try
            {
                tv.Nodes.Clear();

                var s = new Stack<IndexContainer>();
                s.Push(new IndexContainer());
                FillTreeView(tv.Nodes.Add("ROOT"), JsonConvert.DeserializeObject<JToken>(JsonConvert.SerializeObject(obj)), s);
                s.Pop();
            }
            finally
            {
                tv.EndUpdate();
            }
        }
    }
}

You can call it as so:

treeView1.SetObjectAsJson(new MyNeatObject());
like image 96
Andy Avatar answered Oct 27 '22 03:10

Andy