2010-08-14 46 views
17

Tôi đang chuyển đổi dữ liệu của mình thành danh sách chung C#.Làm thế nào để chuyển đổi danh sách chung C# thành json bằng json.net?

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

Bây giờ làm cách nào tôi có thể chuyển đổi số này list thành json bằng json.net? Bất kì lời đề nghị nào.

Mẫu định dạng json nên như thế này,

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

Trả lời

23

Dưới đây là một ví dụ:

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); 
    } 
} 

Tài liệu: LINQ to JSON with Json.NET

+0

ví dụ sử dụng LINQ nhưng tôi muốn sử dụng danh sách chung –

+3

@Pandiya: Vì vậy, chỉ cần thay đổi 'table.AsEnumerable()' bit thành 'list'. Cho rằng bạn đang sử dụng 'DataTable' trong ví dụ của bạn, tôi nghĩ bạn muốn có một' DataTable' làm nguồn ban đầu của bạn ... nếu không thì tại sao bạn lại bận tâm với đoạn mã đó? –

Các vấn đề liên quan