【问题标题】:How to convert c# generic list to json using json.net?如何使用 json.net 将 c# 通用列表转换为 json?
【发布时间】:2011-03-29 18:38:59
【问题描述】:

我正在将我的数据表转换为 c# 通用列表。

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

现在我如何使用 json.net 将此 list 转换为 json?任何建议。

json格式的样本应该是这样的,

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

【问题讨论】:

    标签: c# json generics list json.net


    【解决方案1】:

    这是一个例子:

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

    文档:LINQ to JSON with Json.NET

    【讨论】:

    • 示例使用 linq 但我想使用通用列表
    • @Pandiya:所以只需将table.AsEnumerable() 位更改为list。鉴于您在示例中使用了DataTable,我认为您想要DataTable 作为您的原始来源......否则您为什么要为那段代码烦恼?
    【解决方案2】:
    var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string sJSON = oSerializer.Serialize(yourList);
    

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

    【讨论】:

    • 这似乎对我不起作用,sJON 返回空{}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多