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();
}