如何使用 json.net 将 c# 通用列表转换为 json? [英] How to convert c# generic list to json using json.net?

查看:23
本文介绍了如何使用 json.net 将 c# 通用列表转换为 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am converting my datatable to c# generic list.

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

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

Now how can i convert this list to json using json.net? Any suggestion.

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

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

推荐答案

这是一个例子:

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使用 Json.NET

这篇关于如何使用 json.net 将 c# 通用列表转换为 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆