Search code examples
c#json.netobjectlistviewtreelistview

InvalidCastException upon displaying JSON data into a tree structure using TreeListView


My JSON looks like this:

[
    {
        "id": 001,
        "name": "Item 1",
        "tree": [
            "010",
            "020",
            "030"
        ]
    },
    {
        "id": 002,
        "name": "Item 2",
        "tree": [
            "010",
            "020",
            "030"
        ]
    },
        {
        "id": 003,
        "name": "Item 3",
        "tree": [
            "010",
            "020",
            "030"
        ]
    }
]

This can be modelled into C# as following:

public class Product
{
    public int id { get; set; }
    public string name { get; set; }
    public List<string> tree { get; set; }
}

I'm trying to display this JSON data into a TreeListView in the ObjectListView libary. Ideally, it would look like this.

enter image description here

My current code is as following, with "data" being the TreeListView.

List<Product> Products = JsonConvert.DeserializeObject<List<Product>>(json);

data.CanExpandGetter = model => ((Product)model).tree.Count > 0;

data.ChildrenGetter = delegate(object model)
{
    return ((Product)model).
            tree;
};

data.SetObjects(Products);

However, this throws an System.InvalidCastException at model => ((Product)model).tree.Count > 0.


Solution

  • I found the solution. I changed the JSON layout a bit.

    public class ProductJSON
    {
        public string id { get; set; }
        public string name { get; set; }
        public List<Tree> tree { get; set; }
    }
    public class Tree
    {
        public string id { get; set; }
        public string name { get; set; }
    }
    
    public class Product
    {
        public string id { get; set; }
        public string name { get; set; }
        public List<Product> tree { get; set; }
        public Product(string _id, string _name)
        {
            id = _id;
            name = _name;
            tree = new List<Product>();
        }   
    }
    

    ...

    List<ProductJSON> Products = JsonConvert.DeserializeObject<List<ProductJSON>>(json);
    
    List<Product> ProductList = new List<Product>();
    for(int i = 0; i < Products.Count; i++)
    {
        ProductList.Add(new Product(Products[i].id, Products[i].name));
        foreach (Tree t in Products[i].tree)
        {
            ProductList[i].tree.Add(new Product(t.id, t.name));
        }
    }
    data.CanExpandGetter = delegate(object x) { return true; };
    data.ChildrenGetter = delegate(object x) { return ((Product)x).tree; };
    cID.AspectGetter = delegate(object x) { return String.Format("{0,3:D3}", ((Product)x).id); };
    cName.AspectGetter = delegate(object x) { return ((Product)x).name; };
    data.Roots = ProductList;