0

我的 JSON 看起来像这样:

[
    {
        "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"
        ]
    }
]

这可以建模为 C#,如下所示:

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

我正在尝试将此 JSON 数据显示到 ObjectListView 库中的 TreeListView 中。理想情况下,它看起来像这样。

在此处输入图像描述

我当前的代码如下,“数据”是 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);

但是,这会引发System.InvalidCastExceptionat model => ((Product)model).tree.Count > 0

4

1 回答 1

0

我找到了解决方案。我稍微改变了 JSON 布局。

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;
于 2014-05-29T08:36:09.873 回答