2013-07-26 76 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); 

上面的代码产生下面的字符串...

{ “汽车总动员”: “本田”, “福特” ], “人物”: “哈里森·福特”, “精神科”, “杰西卡·阿尔芭” ], “公司”: “甲骨文”, “微软” ] }