Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"}]}
like image 913
ACP Avatar asked Aug 14 '10 06:08

ACP


People also ask

How do you convert Celsius to Fahrenheit easy?

To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

What is the formula to C?

In order to convert Fahrenheit to Celsius, we use the formula, °C = (°F - 32) × 5/9, in which the value of the temperature in Fahrenheit is placed and we get the value in Celsius. Fahrenheit and Celsius are the scales that are used to measure temperature.

How do you convert Celsius to normal values?

Celsius to Fahrenheit Conversion FormulaMultiply the °C temperature by 1.8. Add 32 to this number. This is the answer in °F.

How do you calculate degrees in C?

Celsius to Fahrenheit : F = (9/5 × °C) + 32. Fahrenheit to Celsius: C= 5/9(°F - 32) Kelvin to Celsius: C= K - 273.


1 Answers

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

like image 123
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet