如何使用json.net将c#通用列表转换为json?

前端之家收集整理的这篇文章主要介绍了如何使用json.net将c#通用列表转换为json?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我将我的datatable转换为c#通用列表。
  1. DataTable dt = mydata();
  2. List<DataRow> list = dt.AsEnumerable().ToList();

现在我如何使用json.net将此列表转换为json?任何建议。

json格式的样本应该是这样的,

  1. {"Table" : [{"userid" : "1","name" : "xavyTechnologies","designation" : "","phone" : "9999999999","email" : "test@test.com","role" : "Admin","empId" : "","reportingto" : ""},{"userid" : "2","name" : "chendurpandian","designation" :
  2. "softwaredeveloper","phone" : "9566643707","email" : "chendur.pandia@gmail.com","role" : "Super User","empId" : "1","reportingto" : "xavyTechnologies"},{"userid" : "3","name" : "sabarinathan","designation" : "marketer","phone" :
  3. "66666666666","email" : "bala3569@gmail.com","role" : "User","empId" : "2","reportingto" : "chendurpandian"}]}
这里有一个例子:
  1. using System;
  2. using System.Data;
  3. using Newtonsoft.Json.Linq;
  4.  
  5. class Test
  6. {
  7. static void Main()
  8. {
  9. DataTable table = new DataTable();
  10. table.Columns.Add("userid");
  11. table.Columns.Add("phone");
  12. table.Columns.Add("email");
  13.  
  14. table.Rows.Add(new[] { "1","9999999","test@test.com" });
  15. table.Rows.Add(new[] { "2","1234567","foo@test.com" });
  16. table.Rows.Add(new[] { "3","7654321","bar@test.com" });
  17.  
  18. var query = from row in table.AsEnumerable()
  19. select new {
  20. userid = (string) row["userid"],phone = (string) row["phone"],email = (string) row["email"]
  21. };
  22.  
  23. JObject o = JObject.FromObject(new
  24. {
  25. Table = query
  26. });
  27.  
  28. Console.WriteLine(o);
  29. }
  30. }

文件LINQ to JSON with Json.NET

猜你在找的Json相关文章