How to convert c# generic list to json using json.

2019-01-11 06:58发布

问题:

I am converting my datatable to c# generic list.

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

Now how can i convert this list to json using json.net? Any suggestion.

Sample of json format should be like this,

{"Table" : [{"userid" : "1","name" : "xavyTechnologies","designation" : "",
"phone" : "9999999999","email" : "test@test.com","role" : "Admin","empId" : "",
 "reportingto" : ""},{"userid" : "2","name" : "chendurpandian","designation" :
 "softwaredeveloper","phone" : "9566643707","email" : "chendur.pandia@gmail.com",
 "role" : "Super User","empId" : "1","reportingto" : "xavyTechnologies"},
{"userid" : "3","name" : "sabarinathan","designation" : "marketer","phone" :
"66666666666","email" : "bala3569@gmail.com","role" : "User",
 "empId" : "2","reportingto" : "chendurpandian"}]}

回答1:

Here's one example:

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", "test@test.com" });
        table.Rows.Add(new[] { "2", "1234567", "foo@test.com" });
        table.Rows.Add(new[] { "3", "7654321", "bar@test.com" });

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

Documentation: LINQ to JSON with Json.NET



回答2:

var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(yourList);

Reference: http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx