json 的相互 转换
using System.Runtime.Serialization.Json;
//json 转化为List集合
public List<T> JSONStringToList<T>(string strJson)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
//List<T> objList = serializer.Deserialize<List<T>>(strJson);
List<T> objList = Deserialize<List<T>>(strJson);
return objList;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
//===================================
/// <summary>
/// DataTable转JsonString
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableToJsonString(DataTable dt)
{
StringBuilder sb = new StringBuilder();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
string row = string.Empty;
for (int i = 0; i < dt.Columns.Count; i++)
{
row += string.Format(",\"{0}\":\"{1}\"", dt.Columns[i].ColumnName, dr[i]);
}
if (row.Length>0)
{
row = row.Remove(0, 1);
}
sb.AppendFormat(",{{{0}}}",row);
}
sb.Remove(0, 1);
sb.Insert(0,"[");
sb.Append("]");
}
return sb.ToString();
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。