如何转换C#泛型列表使用json.net到JSON? [英] How to convert c# generic list to json using json.net?
本文介绍了如何转换C#泛型列表使用json.net到JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为我的数据表转换为C#泛型列表。
DataTable的DT = MYDATA();
清单<&的DataRow GT; 。名单= dt.AsEnumerable()了ToList();
现在我怎么能转换为使用json.net这个列表
来的JSON?任何建议。
JSON格式样本应该是这样的,
{表:[{用户id:1,名:xavyTechnologies,称号:,
手机:9999999999,电子邮件:test@test.com,角色:管理,EMPID:,
reportingto:},{参数userid:2,名称:chendurpandian,名称:
softwaredeveloper,手机:9566643707,电子邮件:chendur.pandia@gmail.com
角色:超级用户,EMPID:1,reportingto:xavyTechnologies},
{将把userid:3,名:sabarinathan,称号:营销,手机:
66666666666,电子邮件:bala3569@gmail.com,角色:用户,
EMPID:2,reportingto:chendurpandian}]}
解决方案
下面是一个例子:
使用系统;
使用System.Data这;
使用Newtonsoft.Json.Linq;类测试
{
静态无效的主要()
{
数据表表=新的DataTable();
table.Columns.Add(用户id);
table.Columns.Add(手机);
table.Columns.Add(电子邮件); table.Rows.Add(新[] {1,9999999,test@test.com});
table.Rows.Add(新[] {2,1234567,foo@test.com});
table.Rows.Add(新[] {3,7654321,bar@test.com}); VAR查询从行=在table.AsEnumerable()
选择新{
用户ID =(字符串)行[将把userid],
手机=(字符串)行[电话],
电子邮件=(字符串)行[电子邮件]
}; JObject O = JObject.FromObject(新
{
表=查询
}); Console.WriteLine(O);
}
}
文件:<一href=\"http://james.newtonking.com/projects/json/help/index.html?topic=html/LINQtoJSON.htm\">LINQ以JSON与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" : "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"}]}
解决方案
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
这篇关于如何转换C#泛型列表使用json.net到JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文