web-dev-qa-db-fra.com

Comment convertir la liste générique C # à JSON en utilisant json.net?

Je convertit mon jeu de données à la liste générique C #.

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

Maintenant, comment puis-je convertir ceci list à JSON en utilisant json.net? Toute suggestion.

L'échantillon de format JSON devrait être comme ça,

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

Voici un exemple:

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 à JSON avec json.net

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

Référence: http://blogs.microsoft.co.il/blogs/pini_daya/archive/2009/03/12/convert-Objects-a-javas-in-c-utilisation-javascriptsérializer.aspx

21
Chorinator