.NET中DataSet转化Json工具类

  1.     /**
  2.      * 方法名称:DataSetToJson Beat1.0
  3.      * 参数介绍:
  4.      * ds-数据集 ||
  5.      * JsonName-Json数据的根元素名称 ||
  6.      * ParName-需要转化数据集中名称的数组 ||
  7.      * 此方法为测试小样版,因我的项目需要而生,.
  8.      * 初步打算做成类库.可以转化DataTable等.
  9.      * 完成时间:2008-03-14 白色情人节
  10.      **/

  11.     private string DataSetToJson(DataSet ds,string JsonName,string[] ParName)
  12.     {
  13.         try
  14.         {
  15.         if(ds==null)
  16.         {
  17.             return "DataSet Is Null ,So I Can't Do It To Json!";
  18.         }
  19.         if (JsonName.Length < 1)
  20.         {
  21.             return "You Set The Json Name Is Wrong!";
  22.         }
  23.         if (ds.Tables[0].Columns.Count < ParName.Length)
  24.         {
  25.             return "You Give The ParName Is Bigger Than DataSet Columns!";
  26.         }
  27.         string josn = "{ \"" + JsonName + "\":[";
  28.         string temp = "";
  29.         for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
  30.         {
  31.             temp = temp + "{";
  32.             for (int i = 0; i < ParName.Length; i++)
  33.             {
  34.                 temp += "\"" + ParName[i] + "\":\"" + ds.Tables[0].Rows[j][ParName[i]] + "\"";
  35.                 if (i != ParName.Length - 1)
  36.                 {
  37.                     temp = temp + ",";
  38.                 }
  39.             }
  40.             temp = temp + "},";
  41.         }
  42.         josn = josn + temp + "]}";
  43.         return josn;
  44.         }
  45.         catch (Exception ex)
  46.         {
  47.             return "Codeing is Error----"+ex.ToString();
  48.         }

  49.     }
复制代码
原文地址:https://www.cnblogs.com/luluping/p/1435428.html