/// <summary> /// 将字典数据转换为Json数据. /// </summary> /// <param name="table">待转的数据字典.</param> /// <param name="unicode">是否进行Unicode编码.</param> /// <returns></returns> public static string ToJson(this Hashtable table, bool unicode) { List <string> list = new List <string>(); try { foreach (KeyValuePair <string, object> temp in table) { if (temp.Key != null && temp.Value != null) { list.Add("\"" + temp.Key + "\":" + (unicode ? Utils.ChineseToUnicode(temp.Value.ToString(), false).Replace("\\\"", "\"") : temp.Value.ToString())); } } } catch (Exception ex) { new ECFException(ex); } return("{" + string.Join(",", list) + "}"); }
/// <summary> /// 获取Json格式的数据 /// Author : XP-PC/Shaipe /// Created: 07-30-2014 /// </summary> /// <param name="value">The value.</param> /// <param name="DataType">Type of the data.</param> /// <param name="unicode">if set to <c>true</c> [unicode].</param> /// <returns>System.String</returns> public static string JsonValueOfType(object value, Type DataType, bool unicode = true) { try { if (value == DBNull.Value) { return("null"); } if (Array.IndexOf(numeric, DataType) > -1) { if (value is decimal) { return(((decimal)value).ToString()); } else { return(ToString(value)); } } if (DataType == typeof(long)) { return(value.ToString()); } // boolean if (DataType == typeof(bool)) { return(((bool)value) ? "true" : "false"); } if (DataType == typeof(byte[])) { byte[] temp = value as byte[]; return(string.Join("", temp)); } // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx \\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\\/ if (DataType == typeof(DateTime)) { return("\"" + value + "\""); } if (value.ToString().IsJson()) // 若字符串为Json格式字符串直接输出不转换为字符串形式输出 { if (unicode) { return(Utils.ChineseToUnicode(value.ToString(), false)); } else { return(value.ToString()); } } else { char emptyChar = (char)127; value = value.ToString().Replace(@"\", @"\\") .Replace(Environment.NewLine, @"\n").Replace("\"", @"\""") .Replace((char)13, emptyChar).Replace((char)10, emptyChar).Replace((char)9, emptyChar); if (unicode) { return("\"" + Utils.ChineseToUnicode(value.ToString(), false) + "\""); } else { return("\"" + value.ToString() + "\""); } } } catch (Exception ex) { ////new ECFException(ex.Message, ex); return(""); } }