2013-07-26 113 views
0

我有兩個集合:如何從動態數據構建JSON?

第一個是「父」節點:

例如

汽車
人民
公司
...

在每個的這些,還有一些數據。

  1. 汽車
    1.1。本田
    1.2。福特
  2. 人民
    2.1。哈里森·福特
    2.2。 Psy
    2.3。傑西卡·奧爾芭
  3. 公司
    3.1。 Oracle
    3.2。微軟

等等...

這些項目,我可以在我的C#應用​​程序遍歷。

我怎麼會去爲了構建一個DataTable(或任何對象將工作最好與它)生產者模仿上面的樹JSON?

這是我有什麼,但它並沒有真正給我什麼,我需要:

public DataTable getNotificationTypeByUser(int id) 
     { 
      var bo = new HomeBO(); 
      var list = bo.GetNotificationsForUser(id); 
      var notificationTreeNode = (from GBLNotifications n in list 
           where n.NotificationCount != 0 
           select new NotificationTreeNode(n)).ToList(); 

      var table = new DataTable(); 

      var column1 = new DataColumn 
      { 
       DataType = Type.GetType("System.String"), 
       ColumnName = "NotificationType" 
      }; 

      table.Columns.Add(column1); 

      var column2 = new DataColumn 
      { 
       DataType = Type.GetType("System.String"), 
       ColumnName = "NotificationDescription" 
      }; 

      table.Columns.Add(column2); 

      foreach (var node in notificationTreeNode) 
      { 
       var row1 = table.NewRow(); 
       row1["NotificationType"] = node.ToString(); 
       table.Rows.Add(row1); 

       var notifications = bo.GetNotificationsForUser(id, node.NotificationNode.NotificationTypeId); 

       foreach (GBLNotifications n in notifications) 
       { 
        var row = table.NewRow(); 
        row["NotificationDescription"] = n.NotificationDescription; 
        table.Rows.Add(row); 
       } 
      } 
      return table; 
     } 

回答

2

假設你已經有了你可以使用任何串行周圍像Newtonsoft的序列化,要JSON

集合

using Newtonsoft.Json; 

string json = JsonConvert.SerializeObject(yourlist); 
+0

這東西,我沒有收藏卻因爲我不知道如何構建它正確 –

+0

你的第一個林e說我有收藏品。無論如何,如果你沒有用適當的字段創建所需的類,而不是添加到數據表中,你可以將它們添加到你的對象列表中 – Ehsan

1

嘛,不知道發生了什麼事在你的代碼,但您的層次結構的描述來看,你需要這樣的對象:

// along with their properties 
public class Car { } 
public class Person { } 
public class Company { } 

public class DataAggregate 
{ 
    public List<Car> Cars { get; set; } 
    public List<Person> People { get; set; } 
    public List<Company> Companies { get; set; } 
} 

然後你連載他們像:

public void SerializeData() 
{ 
    var aggregate = new DataAggregate(); 
    // fill the aggregate accordingly -> from your data source (data tables or what have you) 

    // this now has the JSON format format you're looking for 
    string jsonData = JsonConvert.SerializeObject(aggregate); 
} 

我真希望我沒有誤解你的問題。

0

什麼這一個。

 var Cars = new[] { "Honda", "Ford"}; 
     var People = new[] { "Harrison Ford", "Psy", "Jessica Alba" }; 
     var Companies = new[] { "Oracle", "Microsoft" }; 
     var result = new {Cars, People, Companies }; 
     string json = Newtonsoft.Json.JsonConvert.SerializeObject(result); 

上面的代碼產生下面的字符串...

{ 「汽車總動員」: 「本田」, 「福特」 ], 「人物」: 「哈里森·福特」, 「精神科」, 「傑西卡·阿爾芭」 ], 「公司」: 「甲骨文」, 「微軟」 ] }