博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.net Json JavaScriptSerializer JsonHelper类
阅读量:6250 次
发布时间:2019-06-22

本文共 18110 字,大约阅读时间需要 60 分钟。

结合.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
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 私有方法    ///     /// 过滤特殊字符    ///     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 '\b':                    sb.Append("\\b"); break;                case '\f':                    sb.Append("\\f"); break;                case '\n':                    sb.Append("\\n"); break;                case '\r':                    sb.Append("\\r"); break;                case '\t':                    sb.Append("\\t"); break;                default:                    sb.Append(c); break;            }        }        return sb.ToString();    }    ///     /// 格式化字符型、日期型、布尔型    ///     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    ///     /// List转换成Json    ///     public static string ListToJson
(IList
list) { object obj = list[0]; return ListToJson
(list, obj.GetType().Name); } ///
/// List转换成Json /// public static string ListToJson
(IList
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
(); 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 ///
/// 对象转换为Json /// ///
对象 ///
Json字符串
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 ///
/// 对象集合转换Json /// ///
集合对象 ///
Json字符串
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 ///
/// 普通集合转换Json /// ///
集合对象 ///
Json字符串
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 ///
/// 对象转JSON /// ///
对象 ///
JSON格式的字符串
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 ///
/// DataSet转换为Json /// ///
DataSet对象 ///
Json字符串
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转键值对数组字典 ///
/// 数据集转键值对数组字典 /// ///
数据集 ///
键值对数组字典
public static Dictionary
>> DataSetToDic(DataSet ds) { Dictionary
>> result = new Dictionary
>>(); foreach (DataTable dt in ds.Tables) result.Add(dt.TableName, DataTableToList(dt)); return result; } #endregion #region Datatable转换为Json ///
/// Datatable转换为Json /// ///
Datatable对象 ///
Json字符串
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(); } ///
/// DataTable转换为Json /// 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转键值对集合 ///
/// 数据表转键值对集合 /// 把DataTable转成 List集合, 存每一行 /// 集合中放的是键值对字典,存每一列 /// ///
数据表 ///
哈希表数组
public static List
> DataTableToList(DataTable dt) { List
> list = new List
>(); foreach (DataRow dr in dt.Rows) { Dictionary
dic = new Dictionary
(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } #endregion #region DataTable转List
///
/// DataTable转List
///
///
数据项类型
///
DataTable ///
List数据集
public static List
DataTableToList
(DataTable dt) where T : new() { List
tList = new List
(); 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 ///
/// 数据表转JSON /// ///
数据表 ///
JSON字符串
public static string DataTableToJSON(DataTable dt) { return ObjectToJSON(DataTableToList(dt)); } #endregion #region 泛型集合转DataTable ///
/// 泛型集合转DataTable /// ///
集合类型
///
泛型集合 ///
DataTable
public static DataTable ListToDataTable
(IList
entityList) { if (entityList == null) return null; DataTable dt = CreateTable
(); 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的结构 ///
/// 创建表结构 /// ///
///
private static DataTable CreateTable
() { 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 ///
/// DataReader转换为Json /// ///
DataReader对象 ///
Json字符串
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转实体 ///
/// DataReader转实体 /// ///
数据类型
///
DataReader ///
实体
public static T DataReaderToModel
(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
DBFieldNameList = new List
(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
///
/// DataReader转List
///
///
数据类型
///
DataReader ///
List数据集
public static List
DataReaderToList
(IDataReader dr) where T : new() { List
tList = new List
(); if (dr == null) { dr.Close(); return tList; } using (dr) { PropertyInfo[] propertys = typeof(T).GetProperties(); //获取此实体的公共属性 List
DBFieldNameList = new List
(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 序列化、反序列化 ///
/// 对象序列化 /// ///
///
///
public static String Serialize
(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; } ///
/// 反序列化 /// ///
///
///
public static T Deserialize
(String json) { JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Deserialize
(json); //T o; //json = HttpContext.Current.Server.UrlDecode(json); //JavaScriptSerializer ser = new JavaScriptSerializer(); //ser.MaxJsonLength = Int32.MaxValue; //o = ser.Deserialize
(json); //return o; /* o = Activator.CreateInstance
(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType()); o = (T)(ser.ReadObject(ms)); } */ } #endregion #region JSON文本转对象,泛型方法 ///
/// JSON文本转对象,泛型方法 /// ///
类型
///
JSON文本 ///
指定类型的对象
public static T JSONToObject
(string jsonText) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Deserialize
(jsonText); } catch (Exception ex) { throw new Exception("JSONHelper.JSONToObject(): " + ex.Message); } } #endregion #region 将JSON文本转换为数据表数据 ///
/// 将JSON文本转换为数据表数据 /// ///
JSON文本 ///
数据表字典
public static Dictionary
>> TablesDataFromJSON(string jsonText) { return JSONToObject
>>>(jsonText); } #endregion #region 将JSON文本转换成数据行 ///
/// 将JSON文本转换成数据行 /// ///
JSON文本 ///
数据行的字典
public static Dictionary
DataRowFromJSON(string jsonText) { return JSONToObject
>(jsonText); } #endregion}

 后台Http请求

///     ///     ///     /// 网址    /// 参数    /// 编码格式     /// 
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; } }
View Code

 

转载于:https://www.cnblogs.com/yonsy/p/4446958.html

你可能感兴趣的文章
10.常见数据库操作1
查看>>
JavaScript高级-定义函数(类)方法
查看>>
移动web图片高度自适应的解决方案
查看>>
API
查看>>
需求获取的前期工作(不断更新)
查看>>
10.23
查看>>
hdu5420 Victor and Proposition
查看>>
如何编写可移植的c/c++代码
查看>>
#pragma pack(n)
查看>>
IntelliJ IDEA 2018.3 升级功能介绍
查看>>
基于.NET平台常用的框架整理
查看>>
【每天一道算法题】Lucky String
查看>>
整合apache+tomcat+keepalived实现高可用tomcat集群
查看>>
计算几何-HPI
查看>>
香农熵学习+例子[转载]
查看>>
利用DE2上的WM8731D/A转换器产生正弦波
查看>>
清除EasyUi combotree下拉树的值
查看>>
手写RPC框架
查看>>
Hadoop 分片、分组与排序
查看>>
使用Windows8开发Metro风格应用一
查看>>