结合.net 的JavaScriptSerializer 类实现Json数据处理
调用1:
Model.Users m = BLL.UsersBLL.GetUserById(Convert.ToInt32(id)); string result = ""; if (m != null) result = JsonHelper.ObjectToJSON(m); context.Response.Write(result);
调用2:
Hashtable ht = new Hashtable(); List<Model.UsersModel> resultlist = BLL.UsersBLL.GetUsersList(type, begin, end, page, 4, ht); string result = JsonHelper.ObjectToJSON( new { @list = resultlist, @today = DateTime.Now.ToString("yyyy-MM-dd"), @pageIndex = page, @recordCount = ht["rowcount"], @pageCount = ht["pagecount"] }); context.Response.Write(result);
//////////////////////////////////////////////////////////
前台JS调用Json数据
$.ajax({
url: "../handler/zeji.ashx",
type: "POST",
data: "type=" + type + "&time=" + time + "&page=" + page,
//completed: $("#indicator").hide(),
success: function (data) {
data = eval("(" + data + ")");
for (var i = 0; i < data.list.length; i++) {
var riqi = data.list[i].Riqi.toString();
}
var recordCount = data.recordCount;
}
});
JsonHelper 类
public class JsonHelper { #region 私有方法 /// <summary> /// 过滤特殊字符 /// </summary> private static string StringToJson(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.Length; i++) { char c = s.ToCharArray()[i]; switch (c) { case '"': sb.Append("\""); break; case '\': sb.Append("\\"); break; case '/': sb.Append("\/"); break; case '': sb.Append("\b"); break; case 'f': sb.Append("\f"); break; case ' ': sb.Append("\n"); break; case ' ': sb.Append("\r"); break; case ' ': sb.Append("\t"); break; default: sb.Append(c); break; } } return sb.ToString(); } /// <summary> /// 格式化字符型、日期型、布尔型 /// </summary> private static string StringFormat(string str, Type type) { if (type == typeof(string)) { str = StringToJson(str); str = """ + str + """; } else if (type == typeof(DateTime)) { str = """ + str + """; } else if (type == typeof(bool)) { str = str.ToLower(); } else if (type != typeof(string) && string.IsNullOrEmpty(str)) { str = """ + str + """; } return str; } #endregion #region List转换成Json /// <summary> /// List转换成Json /// </summary> public static string ListToJson<T>(IList<T> list) { object obj = list[0]; return ListToJson<T>(list, obj.GetType().Name); } /// <summary> /// List转换成Json /// </summary> public static string ListToJson<T>(IList<T> list, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name; Json.Append("{"" + jsonName + "":["); if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { T obj = Activator.CreateInstance<T>(); PropertyInfo[] pi = obj.GetType().GetProperties(); Json.Append("{"); for (int j = 0; j < pi.Length; j++) { Type type = pi[j].GetValue(list[i], null).GetType(); Json.Append(""" + pi[j].Name.ToString() + "":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type)); if (j < pi.Length - 1) { Json.Append(","); } } Json.Append("}"); if (i < list.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion #region 对象转换为Json /// <summary> /// 对象转换为Json /// </summary> /// <param name="jsonObject">对象</param> /// <returns>Json字符串</returns> public static string ToJson(object jsonObject) { string jsonString = "{"; PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties(); for (int i = 0; i < propertyInfo.Length; i++) { object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null); string value = string.Empty; if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan) { value = "'" + objectValue.ToString() + "'"; } else if (objectValue is string) { value = "'" + ToJson(objectValue.ToString()) + "'"; } else if (objectValue is IEnumerable) { value = ToJson((IEnumerable)objectValue); } else { value = ToJson(objectValue.ToString()); } jsonString += """ + ToJson(propertyInfo[i].Name) + "":" + value + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "}"; } #endregion #region 对象集合转换Json /// <summary> /// 对象集合转换Json /// </summary> /// <param name="array">集合对象</param> /// <returns>Json字符串</returns> public static string ToJson(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString += ToJson(item) + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "]"; } #endregion #region 普通集合转换Json /// <summary> /// 普通集合转换Json /// </summary> /// <param name="array">集合对象</param> /// <returns>Json字符串</returns> public static string ToArrayString(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString = ToJson(item.ToString()) + ","; } jsonString.Remove(jsonString.Length - 1, jsonString.Length); return jsonString + "]"; } #endregion #region Object转JSON /// <summary> /// 对象转JSON /// </summary> /// <param name="obj">对象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJSON(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); } } #endregion #region DataSet转换为Json /// <summary> /// DataSet转换为Json /// </summary> /// <param name="dataSet">DataSet对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataSet dataSet) { string jsonString = "{"; foreach (DataTable table in dataSet.Tables) { jsonString += """ + table.TableName + "":" + ToJson(table) + ","; } jsonString = jsonString.TrimEnd(','); return jsonString + "}"; } #endregion #region DataSet转键值对数组字典 /// <summary> /// 数据集转键值对数组字典 /// </summary> /// <param name="dataSet">数据集</param> /// <returns>键值对数组字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds) { Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>(); foreach (DataTable dt in ds.Tables) result.Add(dt.TableName, DataTableToList(dt)); return result; } #endregion #region Datatable转换为Json /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table">Datatable对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataTable dt) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { jsonString.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; string strValue = drc[i][j].ToString(); Type type = dt.Columns[j].DataType; jsonString.Append(""" + strKey + "":"); strValue = StringFormat(strValue, type); if (j < dt.Columns.Count - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } /// <summary> /// DataTable转换为Json /// </summary> public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{"" + jsonName + "":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { Type type = dt.Rows[i][j].GetType(); Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + StringFormat(dt.Rows[i][j].ToString(), type)); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("]}"); return Json.ToString(); } #endregion #region DataTable转键值对集合 /// <summary> /// 数据表转键值对集合 /// 把DataTable转成 List集合, 存每一行 /// 集合中放的是键值对字典,存每一列 /// </summary> /// <param name="dt">数据表</param> /// <returns>哈希表数组</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> dic = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } #endregion #region DataTable转List<T> /// <summary> /// DataTable转List<T> /// </summary> /// <typeparam name="T">数据项类型</typeparam> /// <param name="dt">DataTable</param> /// <returns>List数据集</returns> public static List<T> DataTableToList<T>(DataTable dt) where T : new() { List<T> tList = new List<T>(); if (dt == null || dt.Rows.Count == 0) { return tList; } PropertyInfo[] propertys = typeof(T).GetProperties(); //获取此实体的公共属性 foreach (DataRow dr in dt.Rows) { T t = new T(); foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) { continue; } string columnName = pi.Name; if (dr.Table.Columns.Contains(columnName)) { // 判断此属性是否有Setter或columnName值是否为空 object value = dr[columnName]; if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite) { continue; } #region SetValue try { switch (pi.PropertyType.ToString()) { case "System.String": pi.SetValue(t, Convert.ToString(value), null); break; case "System.ToChar": pi.SetValue(t, Convert.ToChar(value), null); break; case "System.Int64": pi.SetValue(t, Convert.ToInt64(value), null); break; case "System.Int32": pi.SetValue(t, Convert.ToInt32(value), null); break; case "System.ToUInt64": pi.SetValue(t, Convert.ToUInt64(value), null); break; case "System.ToUInt32": pi.SetValue(t, Convert.ToUInt32(value), null); break; case "System.DateTime": pi.SetValue(t, Convert.ToDateTime(value), null); break; case "System.Boolean": pi.SetValue(t, Convert.ToBoolean(value), null); break; case "System.Double": pi.SetValue(t, Convert.ToDouble(value), null); break; case "System.Decimal": pi.SetValue(t, Convert.ToDecimal(value), null); break; case "System.Single": pi.SetValue(t, Convert.ToSingle(value), null); break; default: pi.SetValue(t, value, null); break; } } catch { //throw (new Exception(ex.Message)); } #endregion } } tList.Add(t); } return tList; } #endregion #region DataTable转JSON /// <summary> /// 数据表转JSON /// </summary> /// <param name="dataTable">数据表</param> /// <returns>JSON字符串</returns> public static string DataTableToJSON(DataTable dt) { return ObjectToJSON(DataTableToList(dt)); } #endregion #region 泛型集合转DataTable /// <summary> /// 泛型集合转DataTable /// </summary> /// <typeparam name="T">集合类型</typeparam> /// <param name="entityList">泛型集合</param> /// <returns>DataTable</returns> public static DataTable ListToDataTable<T>(IList<T> entityList) { if (entityList == null) return null; DataTable dt = CreateTable<T>(); Type entityType = typeof(T); //PropertyInfo[] properties = entityType.GetProperties(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (T item in entityList) { DataRow row = dt.NewRow(); foreach (PropertyDescriptor property in properties) { row[property.Name] = property.GetValue(item); } dt.Rows.Add(row); } return dt; } #endregion #region 创建DataTable的结构 /// <summary> /// 创建表结构 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> private static DataTable CreateTable<T>() { Type entityType = typeof(T); //PropertyInfo[] properties = entityType.GetProperties(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); //生成DataTable的结构 DataTable dt = new DataTable(); foreach (PropertyDescriptor prop in properties) { dt.Columns.Add(prop.Name); } return dt; } #endregion #region DataReader转换为Json /// <summary> /// DataReader转换为Json /// </summary> /// <param name="dataReader">DataReader对象</param> /// <returns>Json字符串</returns> public static string ToJson(DbDataReader dataReader) { StringBuilder jsonString = new StringBuilder(); jsonString.Append("["); while (dataReader.Read()) { jsonString.Append("{"); for (int i = 0; i < dataReader.FieldCount; i++) { Type type = dataReader.GetFieldType(i); string strKey = dataReader.GetName(i); string strValue = dataReader[i].ToString(); jsonString.Append(""" + strKey + "":"); strValue = StringFormat(strValue, type); if (i < dataReader.FieldCount - 1) { jsonString.Append(strValue + ","); } else { jsonString.Append(strValue); } } jsonString.Append("},"); } dataReader.Close(); jsonString.Remove(jsonString.Length - 1, 1); jsonString.Append("]"); return jsonString.ToString(); } #endregion #region DataReader转实体 /// <summary> /// DataReader转实体 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="dr">DataReader</param> /// <returns>实体</returns> public static T DataReaderToModel<T>(IDataReader dr) where T : new() { T t = new T(); if (dr == null) { dr.Close(); return default(T); } using (dr) { if (dr.Read()) { PropertyInfo[] propertys = t.GetType().GetProperties(); //获取此实体的公共属性 List<string> DBFieldNameList = new List<string>(dr.FieldCount); for (int i = 0; i < dr.FieldCount; i++) { DBFieldNameList.Add(dr.GetName(i).ToLower()); } foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) { continue; } string columnName = pi.Name; if (DBFieldNameList.Contains(columnName.ToLower())) { //判断此属性是否有Setter或columnName值是否为空 object value = dr[columnName]; if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite) { continue; } #region SetValue try { switch (pi.PropertyType.ToString()) { case "System.String": pi.SetValue(t, Convert.ToString(value), null); break; case "System.ToChar": pi.SetValue(t, Convert.ToChar(value), null); break; case "System.Int64": pi.SetValue(t, Convert.ToInt64(value), null); break; case "System.Int32": pi.SetValue(t, Convert.ToInt32(value), null); break; case "System.ToUInt64": pi.SetValue(t, Convert.ToUInt64(value), null); break; case "System.ToUInt32": pi.SetValue(t, Convert.ToUInt32(value), null); break; case "System.DateTime": pi.SetValue(t, Convert.ToDateTime(value), null); break; case "System.Boolean": pi.SetValue(t, Convert.ToBoolean(value), null); break; case "System.Double": pi.SetValue(t, Convert.ToDouble(value), null); break; case "System.Decimal": pi.SetValue(t, Convert.ToDecimal(value), null); break; case "System.Single": pi.SetValue(t, Convert.ToSingle(value), null); break; default: pi.SetValue(t, value, null); break; } } catch { //throw (new Exception(ex.Message)); } #endregion } } } } dr.Close(); return t; } #endregion #region DataReader转List<T> /// <summary> /// DataReader转List<T> /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="dr">DataReader</param> /// <returns>List数据集</returns> public static List<T> DataReaderToList<T>(IDataReader dr) where T : new() { List<T> tList = new List<T>(); if (dr == null) { dr.Close(); return tList; } using (dr) { PropertyInfo[] propertys = typeof(T).GetProperties(); //获取此实体的公共属性 List<string> DBFieldNameList = new List<string>(dr.FieldCount); for (int i = 0; i < dr.FieldCount; i++) { DBFieldNameList.Add(dr.GetName(i).ToLower()); } while (dr.Read()) { T t = new T(); foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) { continue; } string columnName = pi.Name; if (DBFieldNameList.Contains(columnName.ToLower())) { // 判断此属性是否有Setter或columnName值是否为空 object value = dr[columnName]; if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite) { continue; } #region SetValue try { switch (pi.PropertyType.ToString()) { case "System.String": pi.SetValue(t, Convert.ToString(value), null); break; case "System.ToChar": pi.SetValue(t, Convert.ToChar(value), null); break; case "System.Int64": pi.SetValue(t, Convert.ToInt64(value), null); break; case "System.Int32": pi.SetValue(t, Convert.ToInt32(value), null); break; case "System.ToUInt64": pi.SetValue(t, Convert.ToUInt64(value), null); break; case "System.ToUInt32": pi.SetValue(t, Convert.ToUInt32(value), null); break; case "System.DateTime": pi.SetValue(t, Convert.ToDateTime(value), null); break; case "System.Boolean": pi.SetValue(t, Convert.ToBoolean(value), null); break; case "System.Double": pi.SetValue(t, Convert.ToDouble(value), null); break; case "System.Decimal": pi.SetValue(t, Convert.ToDecimal(value), null); break; case "System.Single": pi.SetValue(t, Convert.ToSingle(value), null); break; default: pi.SetValue(t, value, null); break; } } catch { //throw (new Exception(ex.Message)); } #endregion } } tList.Add(t); } } dr.Close(); return tList; } #endregion #region 序列化、反序列化 /// <summary> /// 对象序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static String Serialize<T>(T obj) { String s; JavaScriptSerializer ser = new JavaScriptSerializer(); ser.MaxJsonLength = Int32.MaxValue; s = ser.Serialize(obj); /* DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, obj); s = Encoding.Default.GetString(ms.ToArray()); } */ return s; } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Deserialize<T>(String json) { JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Deserialize<T>(json); //T o; //json = HttpContext.Current.Server.UrlDecode(json); //JavaScriptSerializer ser = new JavaScriptSerializer(); //ser.MaxJsonLength = Int32.MaxValue; //o = ser.Deserialize<T>(json); //return o; /* o = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType()); o = (T)(ser.ReadObject(ms)); } */ } #endregion #region JSON文本转对象,泛型方法 /// <summary> /// JSON文本转对象,泛型方法 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定类型的对象</returns> public static T JSONToObject<T>(string jsonText) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Deserialize<T>(jsonText); } catch (Exception ex) { throw new Exception("JSONHelper.JSONToObject(): " + ex.Message); } } #endregion #region 将JSON文本转换为数据表数据 /// <summary> /// 将JSON文本转换为数据表数据 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>数据表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText) { return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText); } #endregion #region 将JSON文本转换成数据行 /// <summary> /// 将JSON文本转换成数据行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>数据行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText) { return JSONToObject<Dictionary<string, object>>(jsonText); } #endregion }
后台Http请求
/// <summary> /// /// </summary> /// <param name="url">网址</param> /// <param name="parase">参数</param> /// <param name="encoding">编码格式 </param> /// <returns></returns> public static string GetHttpPost(string url, string encoding) { if (encoding == null) encoding = "gb2312"; try { WebClient WC = new WebClient(); WC.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); int p = url.IndexOf("?"); string sData = url.Substring(p + 1); url = url.Substring(0, p); byte[] postData = Encoding.GetEncoding(encoding).GetBytes(sData); byte[] responseData = WC.UploadData(url, "POST", postData); string ct = Encoding.GetEncoding(encoding).GetString(responseData); return ct; } catch (Exception Ex) { return Ex.Message; } }