JSONHelper
标签:des style blog class c code
///
/// DataTable 转换为JSON 字符串
///
///
///
public static string ToJson(this DataTable dt)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionarystring, object> dictionary = new Dictionarystring, object>(); //实例化一个参数集合
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
}
arrayList.Add(dictionary); //ArrayList集合中添加键值
}
return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串
}
#endregion
#region JSON 字符串 转换为 DataTable数据集合
///
/// JSON 字符串 转换为 DataTable数据集合
///
///
///
public static DataTable ToDataTable(this string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize(json);
if (arrayList.Count > 0)
{
foreach (Dictionarystring, object> dictionary in arrayList)
{
if (dictionary.Keys.Countstring>() == 0)
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch
{
}
result = dataTable;
return result;
}
#endregion
#region 转换为string字符串类型
///
/// 转换为string字符串类型
///
/// 获取需要转换的值
/// 需要格式化的位数
/// 返回一个新的字符串
public static string ToStr(this object s, string format = "")
{
string result = "";
try
{
if (format == "")
{
result = s.ToString();
}
else
{
result = string.Format("{0:" + format + "}", s);
}
}
catch
{
}
return result;
}
JSONHelper,搜素材,soscw.com
JSONHelper
标签:des style blog class c code
原文地址:http://www.cnblogs.com/siyunianhua/p/3738131.html
评论