2015-09-04 51 views
1

我想從C#數據表建立一個JSON輸出。單個數據表也包含父級和子級。我想使用LINQ來設置JSON數據,但是想避免創建類,因爲我有很多這樣的需求,並且爲每個類創建類都是一個負擔。與父母和孩子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' 

請提供更好的代碼(如果有)。在此先感謝

+0

你能告訴我們你試過了什麼嗎? – Thijs

+0

與現有的表一起,我創建了具有不同HEAD的另一個表。並試圖使用LINQ,但我得到了錯誤結果視圖=在'APP-SERVICE.dll'和'CommonLanguageRuntimeLibrary'中都存在類型'<> f__AnonymousType0 '。因爲我期待更好的代碼,所以我不想發佈我的代碼。如果您需要,我會發布。 –

回答

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); 
+0

感謝您的代碼,它工作得很好。我可以要求您更改嗎?我想輸出爲{頭:'體育',總數:300,數據:[{項目:'保時捷911',數量:100},{項目:'保時捷912',數量:200}]}。能否請你幫忙?我會嘗試根據你的代碼學習。謝謝! –

+0

@VyasRao請一次提出一個問題。如果您還有其他問題,請提出一個新問題。 – Eser

+0

打開新的問題,請你檢查http://stackoverflow.com/questions/32398821/datatable-with-parent-and-child-to-json-format-with-hierarchy –

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}] 

}

+0

你的代碼必須正常工作,但我不想創建另一個類。原因是我必須創建許多這樣的JSON對象,並且它使代碼變得混亂。 –