最新更新,平時使用的jsonHelper類,分享給你們使用。json
注:須要引用Json.Net類庫。數組
public class JsonHelper { /// <summary> /// string擴展方法(忽略大小寫比較字符串) /// </summary> /// <param name="source">源字符串</param> /// <param name="value">目標字符串</param> /// <param name="comparisonType"></param> public static bool Contains(string source, string value, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { return source.IndexOf(value, comparisonType) >= 0; } /// <summary> /// 對象轉JSON /// </summary> /// <param name="obj">對象</param> /// <returns>JSON格式的字符串</returns> public static string ObjectToJson(object obj) { try { return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } catch (Exception ex) { throw new Exception(string.Format("JSONHelper.ObjectToJSON()異常:{0} 數據:{1} ", ex.Message, obj)); } } /// <summary> /// 獲取Json格式返回結果 /// </summary> /// <param name="result">操做結果返回類型</param> /// <param name="data">返回數據</param> /// <param name="msg">結果描述</param> /// <returns>Json格式數據,形如{"result":1,"data":0,"msg":""}</returns> public static string GetJsonResult(BackType result, object data, string msg) { var dic = new Dictionary<string, object>(); dic.Add(JsonItem.Result, result.GetHashCode()); dic.Add(JsonItem.Data, data); dic.Add(JsonItem.Msg, msg); return ObjectToJson(dic); } /// <summary> /// 輸出成功數據 /// </summary> /// <param name="data">返回數據</param> /// <param name="msg">返回信息</param> public static void ResponseOK(System.Web.HttpContext cnt, object data, string msg = "請求成功") { var json = GetJsonResult(BackType.Success, data, msg); cnt.Response.Write(json); } /// <summary> /// 輸出失敗數據 /// </summary> /// <param name="data">返回數據</param> /// <param name="msg">返回信息</param> public static void ResponseFail(System.Web.HttpContext cnt, object data, string msg) { var json = GetJsonResult(BackType.Failure, data, msg); cnt.Response.Write(json); } /// <summary> /// 輸出驗證錯誤數據 /// </summary> /// <param name="data">返回數據</param> /// <param name="msg">返回信息</param> public static void ResponseErr(System.Web.HttpContext cnt, object data, string msg) { var json = GetJsonResult(BackType.CheckErr, data, msg); cnt.Response.Write(json); } /// <summary> /// DataTable轉數組集合(輸出字段名全小寫) /// </summary> /// <param name="dt">數據表</param> /// <returns>符合Json格式轉換數據集</returns> public static Dictionary<string, object> DataTableToDic(DataTable dt) { var dic = new Dictionary<string, object>(); var list = new List<object>(); if (dt != null) { var rows = dt.Rows.Count; var cols = dt.Columns.Count; dic.Add(JsonItem.Count, rows);//總記錄數 for (int i = 0; i < rows; i++) { var row = new Dictionary<string, object>(); for (int j = 0; j < cols; j++) { row.Add(dt.Columns[j].ColumnName.ToLower(), dt.Rows[i][j]); } list.Add(row); } } else { dic.Add(JsonItem.Count, 0); } dic.Add(JsonItem.List, list);//數據列表 return dic; } /// <summary> /// DataTable轉Json格式(輸出字段名全小寫) /// </summary> /// <param name="dt">數據表</param> /// <returns>Json格式數據,形如:{"result":1,"data":{"count":0,"list":[{},{}]},"msg":"成功"}</returns> public static string DataTableToJson(DataTable dt) { if (dt == null || dt.Rows.Count < 1) { return GetJsonResult(BackType.Failure, "", "數據爲空"); } return GetJsonResult(BackType.Success, DataTableToDic(dt), "請求成功"); } /// <summary> /// DataSet轉Json格式(輸出字段名全小寫) /// </summary> /// <param name="ds">數據集</param> /// <returns>Json格式數據,形如:{"result":1,"data":[{"count":0,"list":[{},{}]},{}],"msg":""}</returns> public static string DataSetToJson(DataSet ds) { if (ds == null || ds.Tables.Count < 1) { return GetJsonResult(BackType.Failure, "", "數據爲空"); } var tbs = new List<object>(); for (int i = 0; i < ds.Tables.Count; i++) { tbs.Add(DataTableToDic(ds.Tables[i])); } return GetJsonResult(BackType.Success, tbs, "table數目:" + tbs.Count); } /// <summary> /// 將實體轉換爲Dictionary /// </summary> /// <typeparam name="T">實體類</typeparam> /// <param name="info">實體實例</param> /// <returns></returns> public static Dictionary<string, object> EntityToDic<T>(T info) where T : class { var dic = new Dictionary<string, object>(); if (info != null) { var type = typeof(T); var fields = type.GetProperties();//實體屬性集合 foreach (var p in fields) { dic.Add(p.Name, p.GetValue(info, null)); } } return dic; } /// <summary> /// 將實體轉換爲Hashtable /// </summary> /// <typeparam name="T">實體類</typeparam> /// <param name="info">實體實例</param> /// <returns></returns> public static Hashtable EntityToHashtable<T>(T info) where T : class { var ht = new Hashtable(); if (info != null) { var type = typeof(T); var fields = type.GetProperties();//實體屬性集合 foreach (var p in fields) { ht.Add(p.Name, p.GetValue(info, null)); } } return ht; } /// <summary> /// Hashtable轉化爲實體 /// </summary> /// <typeparam name="T">實體類型</typeparam> /// <param name="ht">Hashtable數據</param> public static T HashtableToEntity<T>(Hashtable ht) where T : class { var type = typeof(T); var fields = type.GetProperties();//實體屬性集合 var info = (T)GetInstance(type);//構建實例 foreach (var p in fields)//爲實體實例賦值 { if (ht.Count < 1) break; var key = p.Name; if (ht.ContainsKey(key)) { var ovalue = ht[key]; ht.Remove(ovalue); if (ovalue == null || ovalue == DBNull.Value) continue; var ptype = GetStandardType(p.PropertyType); p.SetValue(info, Convert.ChangeType(ovalue, ptype), null); } } return info; } /// <summary> /// 類型轉換字典 /// </summary> private static Dictionary<Type, Type> TypeDic = new Dictionary<Type, Type>{{typeof(bool?),typeof(bool)},{typeof(int?),typeof(int)}, {typeof(long?),typeof(long)},{typeof(decimal?),typeof(decimal)},{typeof(DateTime?),typeof(DateTime)} }; /// <summary> /// 獲取標準類型 /// </summary> public static Type GetStandardType(Type t) { if (TypeDic.ContainsKey(t)) { t = TypeDic[t]; } return t; } /// <summary> /// Json數據轉實體 /// </summary> /// <typeparam name="T">實體類型</typeparam> /// <param name="json">Json數據</param> /// <returns></returns> public static T JsonToEntity<T>(string json) { var type = typeof(T); var fields = type.GetProperties();//實體屬性集合 var info = (T)GetInstance(type);//構建實例 try { var obj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json); var list = obj.Properties(); foreach (var p in fields)//爲實體實例賦值 { var item = list.FirstOrDefault(tp => string.Compare(tp.Name, p.Name, true) == 0); if (item != null && item.Value != null) { var val = item.Value.ToString(); if (String.IsNullOrEmpty(val) || val == "null") continue; var ptype = GetStandardType(p.PropertyType); p.SetValue(info, Convert.ChangeType(val, ptype), null); } } } catch (Exception ex) { TxtLog.LogErr("Json轉實體解析異常:" + ex.Message); } return info; } /// <summary> /// json數據轉字典 /// </summary> /// <param name="json">Json數據</param> public static Dictionary<string, object> JsonToDic(string json) { var dic = new Dictionary<string, object>(); try { var obj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json); var list = obj.Properties(); foreach (var item in list) { dic.Add(item.Name, item.Value); } } catch (Exception ex) { TxtLog.LogErr("Json轉Dic解析異常:" + ex.Message); } return dic; } #region 實例工具方法 /// <summary> /// 實體克隆方法 /// </summary> private static MethodInfo wiseClone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance); /// <summary> /// 實體克隆委託方法 /// </summary> private static Func<object, object> doClone = Delegate.CreateDelegate(typeof(Func<object, object>), wiseClone) as Func<object, object>; /// <summary> /// 對象實例緩存 /// </summary> private static System.Collections.Concurrent.ConcurrentDictionary<string, object> TCache = new System.Collections.Concurrent.ConcurrentDictionary<string, object>(); /// <summary> /// 緩存操做鎖 /// </summary> private static object lockCache = new object(); /// <summary> /// 獲取對象實例 /// </summary> /// <param name="type">對象類型</param> public static object GetInstance(Type type) { object obj; if (!TCache.TryGetValue(type.Name, out obj)) { obj = Activator.CreateInstance(type);//構建實例 lock (lockCache) { TCache.TryAdd(type.Name, obj); } } return doClone(obj); } #endregion }
幫助類中用的的兩個輔助類代碼:緩存
/// <summary> /// 結果返回類型 /// </summary> public enum BackType { /// <summary> /// 驗證錯誤 -1 /// </summary> CheckErr = -1, /// <summary> /// 失敗 0 /// </summary> Failure = 0, /// <summary> /// 成功 1 /// </summary> Success = 1, }
/// <summary> /// JSON數據格式字段 /// </summary> public class JsonItem { /// <summary> /// 結果標識字段 /// </summary> public const string Result = "result"; /// <summary> /// 返回數據字段 /// </summary> public const string Data = "data"; /// <summary> /// 返回信息字段 /// </summary> public const string Msg = "msg"; /// <summary> /// 返回數據--數目字段 /// </summary> public const string Count = "count"; /// <summary> /// 返回數據--列表字段 /// </summary> public const string List = "list"; }