using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemText;
using SystemData;
namespace Common
{
public static class JsonExtensions
{
#region DataSetToJson 擴展方法
/// <summary>
/// DataSetToJson 擴展方法
/// </summary>
/// <param name=ds>要傳入的DataSet</param>
/// <param name=JsonName>Json的名稱</param>
/// <param name=ParName>Json字段名稱</param>
/// <returns>返回JSON字符串</returns>
public static string DataSetToJson(this DataSet ds string JsonName string[] ParName)
{
try
{
if (ds == null)
{
return DataSet Is Null So I Cant Do It To Json!;
}
if (JsonNameLength < )
{
return You Set The Json Name Is Wrong!;
}
if (dsTables[]ColumnsCount < ParNameLength)
{
return You Give The ParName Is Bigger Than DataSet Columns!;
}
string josn = { + JsonName + :[;
string temp = ;
for (int j = ; j < dsTables[]RowsCount; j++)
{
temp = temp + {;
for (int i = ; i < ParNameLength; i++)
{
temp += + ParName[i] + :\ + dsTables[]Rows[j][ParName[i]] + \;
if (i != ParNameLength )
{
temp = temp + ;
}
}
if (j == dsTables[]RowsCount )
{
temp = temp + };
}
else
{
temp = temp + };
}
}
josn = josn + temp + ]};
return josn;
}
catch (Exception ex)
{
return Codeing is Error + exToString();
}
}
#endregion
#region DataSetToJson 擴展方法
/// <summary>
/// DataSetToJson 擴展方法
/// </summary>
/// <param name=ds>要傳入的DataSet</param>
/// <returns>返回JSON字符串<</returns>
public static string DataSetToJson(this DataSet ds)
{
try
{
if (ds == null)
{
return DataSet Is Null So I Cant Do It To Json!;
}
string josn = [;
string temp = ;
for (int j = ; j < dsTables[]RowsCount; j++)
{
temp = temp + {;
for (int i = ; i < dsTables[]ColumnsCount; i++)
{
temp += + dsTables[]Columns[i]ColumnName + :\ + dsTables[]Rows[j][i] + \;
if (i != dsTables[]ColumnsCount )
{
temp = temp + ;
}
}
if (j == dsTables[]RowsCount )
{
temp = temp + };
}
else
{
temp = temp + };
}
}
josn = josn + temp + ];
return josn;
}
catch (Exception ex)
{
return Codeing is Error + exToString();
}
}
#endregion
}
}
From:http://tw.wingwit.com/Article/program/net/201311/13507.html