2010-08-14 68 views
17

我将我的数据表转换为C#通用列表。如何使用json.net将c#通用列表转换为json?

DataTable dt = mydata(); 
List<DataRow> list = dt.AsEnumerable().ToList(); 

现在,我怎么转换这个list使用json.net到JSON?任何建议。

JSON格式的样品应该是这样的,

{"Table" : [{"userid" : "1","name" : "xavyTechnologies","designation" : "", 
"phone" : "9999999999","email" : "[email protected]","role" : "Admin","empId" : "", 
"reportingto" : ""},{"userid" : "2","name" : "chendurpandian","designation" : 
"softwaredeveloper","phone" : "9566643707","email" : "[email protected]", 
"role" : "Super User","empId" : "1","reportingto" : "xavyTechnologies"}, 
{"userid" : "3","name" : "sabarinathan","designation" : "marketer","phone" : 
"66666666666","email" : "[email protected]","role" : "User", 
"empId" : "2","reportingto" : "chendurpandian"}]} 

回答

23

这里有一个例子:

using System; 
using System.Data; 
using Newtonsoft.Json.Linq; 

class Test 
{ 
    static void Main() 
    { 
     DataTable table = new DataTable(); 
     table.Columns.Add("userid"); 
     table.Columns.Add("phone"); 
     table.Columns.Add("email"); 

     table.Rows.Add(new[] { "1", "9999999", "[email protected]" }); 
     table.Rows.Add(new[] { "2", "1234567", "[email protected]" }); 
     table.Rows.Add(new[] { "3", "7654321", "[email protected]" }); 

     var query = from row in table.AsEnumerable() 
        select new { 
         userid = (string) row["userid"], 
         phone = (string) row["phone"], 
         email = (string) row["email"]    
        }; 

     JObject o = JObject.FromObject(new 
     { 
      Table = query 
     }); 

     Console.WriteLine(o); 
    } 
} 

文档:LINQ to JSON with Json.NET

+0

该示例使用linq,但我想使用通用列表 – 2010-08-14 08:11:23

+3

@Pandiya:所以只需将'table.AsEnumerable()'位更改为'list'。鉴于你在你的例子中使用了'DataTable',我以为你想要一个'DataTable'作为你的原始源代码......否则你为什么要打扰那些代码呢? – 2010-08-14 08:13:58

相关问题