18

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" : "[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"}]}

2 Answers 2

25

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", "[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);
    }
}

Documentation: LINQ to JSON with Json.NET

Sign up to request clarification or add additional context in comments.

2 Comments

the example uses linq but i want to use a generic list
@Pandiya: So just change the table.AsEnumerable() bit to list. Given that you were using DataTable in your example, I thought you wanted a DataTable as your original source... otherwise why did you bother with that bit of code?
21
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

1 Comment

This does not seems to be working for me, the sJON returns empty {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.