具有父级和子级到JSON格式的数据表

时间:2015-09-04 11:31:44

标签: c# asp.net json linq datatable

我正在尝试从C#datatable构建JSON输出。单个数据表也包含父级和子级。我想使用LINQ来设置JSON数据,但是我想避免创建类,因为我有很多这样的需求,并且为每个类创建类将是一个负担。

enter image description here

JSON输出应为

{
Sports : [
{item: 'Porsche 911', quantity: 100},
{item: 'Porsche 912', quantity: 200}
],
Luxury : [
{item: 'BMW 3 Series', quantity: 300}
],
Small :[
{item: 'Toyota Corolla', quantity: 400},
{item: 'Mitsubishi Lancer', quantity: 500},
{item: 'Mitsubishi Lancer 2', quantity: 600}
]}

我试过的示例代码

//get current stock
            DataTable dtCurrentStock = inventoryReports.getCurrentStock(currentDate);

            //get distinct item group
            DataTable dtItemGroup = dtCurrentStock.DefaultView.ToTable(true, "HEAD");

            DataSet sd = new DataSet();

            var itemGroup = dtItemGroup.AsEnumerable();
            var items = dtCurrentStock.AsEnumerable();

            var result = itemGroup.Select(group => new {
                groupName = group.Field<string>("HEAD"),
                itemDetl = 
                items.
                Where(item => (item.Field<string>("HEAD") == group.Field<string>("HEAD"))).
                Select(detl => new
                {
                    a = detl.ToString()
                })//.ToList()
            }).ToList();

错误

Results View = The type '<>f__AnonymousType0<a>' exists in both 'APP-SERVICE.dll' and 'CommonLanguageRuntimeLibrary'

如果可以,请提供更好的代码。提前致谢

2 个答案:

答案 0 :(得分:5)

在Linq的帮助下

var obj = dt.AsEnumerable()
            .GroupBy(r => r["Head"])
            .ToDictionary(g => g.Key.ToString(),
                          g => g.Select(r => new {
                                                item = r["Item"].ToString(),
                                                quantity = (int)r["Quantity"]
                                             })
                                .ToArray());

var json = JsonConvert.SerializeObject(obj);

答案 1 :(得分:1)

或者,如果您无法访问JsonConvert,我建议使用标准的System.Web.Script.Serialization.JavaScriptSerializer:

static class Program
{
    static void Main(string[] args)
    {
        var lst = new ListOfMachines();
        lst.Add(new MachineInfo { Head = "Sports", Item = "Porshe 911", Quantity = 100 });
        lst.Add(new MachineInfo { Head = "Sports", Item = "Porshe 912", Quantity = 200 });
        lst.Add(new MachineInfo { Head = "Luxury", Item = "BMW 3 Series", Quantity = 300 });
        lst.Add(new MachineInfo { Head = "Small", Item = "Toyouta Corolla", Quantity = 400 });
        lst.Add(new MachineInfo { Head = "Small", Item = "Mitsubish Lancer", Quantity = 500 });
        lst.Add(new MachineInfo { Head = "Small", Item = "Mitsubish Lancer 2", Quantity = 600 });

        var json = lst.ToJson();

    }
}

public class ListOfMachines : List<MachineInfo>
{
    public string ToJson()
    {
        var initialGroupBy = this.GroupBy(a => a.Head,
                                            t => new { item = t.Item,
                                                quantity = t.Quantity}               
            ).ToDictionary(
                k => k.Key,
                s => s.Select(v => new {
                        item = v.item,
                        quantity = v.quantity
                }));

        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string jsonString = javaScriptSerializer.Serialize(initialGroupBy);
        return jsonString;
    }
}   

public class MachineInfo
{
    public string Head { get; set; }
    public string Item { get; set; }
    public int Quantity { get; set; }
}

此代码提供以下输出:

  {
    "Sports":[{"item":"Porshe 911","quantity":100},{"item":"Porshe      912","quantity":200}],
"Luxury":[{"item":"BMW 3 Series","quantity":300}],
"Small":[{"item":"Toyouta Corolla","quantity":400},{"item":"Mitsubish Lancer","quantity":500},{"item":"Mitsubish Lancer 2","quantity":600}]

}