First of all, we have to fetch the records from the database (MS Sqlserver) into the C# DataTable, or we can add dynamic rows to our DataTable. So our code looks like as written below.
//*
public DataTable getData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
dt.Rows.Add(1, "Satinder Singh", "Bsc Com Sci", "Mumbai");
dt.Rows.Add(2, "Amit Sarna", "Mstr Com Sci", "Mumbai");
dt.Rows.Add(3, "Andrea Ely", "Bsc Bio-Chemistry", "Queensland");
dt.Rows.Add(4, "Leslie Mac", "MSC", "Town-ville");
dt.Rows.Add(5, "Vaibhav Adhyapak", "MBA", "New Delhi");
dt.Rows.Add(6, "Johny Dave", "MCA", "Texas");
return dt;
}
 
方法一:Fetch each data (value), and append to our jsonString StringBuilder. This is how our code looks like
 
public string DataTableToJsonWithStringBuilder(DataTable table)
{
   var jsonString = new StringBuilder();
   if (table.Rows.Count > 0)
   {
   jsonString.Append("[");
   for (int i = 0; i < table.Rows.Count; i++)
   {
   jsonString.Append("{");
   for (int j = 0; j < table.Columns.Count; j++)
   {
   if (j < table.Columns.Count - 1)
   {
   jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
+ "\":" + "\""
+ table.Rows[i][j].ToString() + "\",");
   }
   else if (j == table.Columns.Count - 1)
   {
   jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
+ "\":" + "\""
+ table.Rows[i][j].ToString() + "\"");
   }
   }
   if (i == table.Rows.Count - 1)
   {
   jsonString.Append("}");
   }
   else
   {
   jsonString.Append("},");
   }
   }
   jsonString.Append("]");
   }
return jsonString.ToString();
}
//*
 

方法 2: Convert DataTable to JSON using JavaScriptSerializer:

public string DataTableToJsonWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
 

方法3(推荐): Convert DataTable to JSON using Json.Net DLL (Newtonsoft):

public string DataTableToJsonWithJsonNet(DataTable table)
{
   string jsonString=string.Empty;
   jsonString = JsonConvert.SerializeObject(table);
   return jsonString;
}

Asp.net C# 把 Datatable转换成JSON 字符串的更多相关文章

  1. DataTable转换成json字符串

    将DataTable里面的行转换成json字符串方法: #region DataTable转为json /// <summary> /// DataTable转为json /// < ...

  2. asp.net dataTable转换成Json格式

    /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...

  3. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

  4. C#中对象,字符串,dataTable、DataReader、DataSet,对象集合转换成Json字符串方法。

    C#中对象,字符串,dataTable.DataReader.DataSet,对象集合转换成Json字符串方法. public class ConvertJson { #region 私有方法 /// ...

  5. 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)

    public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...

  6. C# DataTable 转换成JSON数据

    原文:C# DataTable 转换成JSON数据 using System; using System.Collections.Generic; using System.Data; using S ...

  7. dataTable转换成Json格式

    #region dataTable转换成Json格式 /// <summary> /// /// </summary> /// <param name="dt& ...

  8. 将DataTable转换成Json格式

    方法一: 将DataTable数据拼接成json字符串,方法如下: ///<summary> /// dataTable转换成Json格式 ///</summary> ///& ...

  9. Newtonsoft.Json 把对象转换成json字符串

    var resultJson = new { records = rowCount, page = pageindex, //总页数=(总页数+页大小-1)/页大小 total = (rowCount ...

随机推荐

  1. swift 学习笔记[1]

    最近在IMOOK(网站)上自学了下swift , 总结下swift相对其他语言的不同之处 , 方便熟悉其他语言的程序员,熟悉swift语言的特性. 1. swift 的特别之处就是可以在原有的类上 , ...

  2. java中File类的使用

    public class FileLei {    public static void main(String[] args) throws IOException {        //..表示上 ...

  3. ASP.NET MVC 身份认证

    身份认证的好处就是, 如果这个页面没有登录, 刷新后会自动跳到登录页要求登录,保证了应用程序的安全.而Forms 身份认证是web下最常用的,如何配置呢?见下(基于mvc 4) 1.在webconfi ...

  4. SQL:执行顺序

    SELECT语句的执行的逻辑查询处理步骤: (8)SELECT (9)DISTINCT(11)<TOP_specification> <select_list>(1)FROM ...

  5. Python中对时间日期的处理方法简单汇总

    这篇文章主要介绍了Python实用日期时间处理方法汇总,本文讲解了获取当前datetime.获取当天date.获取明天/前N天.获取当天开始和结束时间(00:00:00 23:59:59).获取两个d ...

  6. QString::​arg的用法

    1.用法示例1 String str = QString("%1 %2 %3 %4 %5 %6 %7 %8 %9 %10 %11").arg("1"," ...

  7. android 设颜色透明值

    如:把    <color name="line_gray_tran">#8d8d8d</color> 要设70%的透明值 计算方法:255*0.75=19 ...

  8. ubuntu kylin 14.04安装配置MongoDB v2.6.1(转)

    1.获取最新版本 https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.1.tgz 2.解压并进入bin目录 tar zxvf mongo ...

  9. iOS开发常用代码块(第二弹)

    GCD定时器 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ); dispat ...

  10. List集合的removeAll(Collection<E> col) 和clear方法的区别

    //removeAll()方法private static void testList(){ List<String> list = new ArrayList<String> ...