using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections; using System.Text; using System.Xml; namespace DopInterfacePlatform { public static class StringHelper { private static int[] numbers = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; /// /// 随机字符串数组集合 /// private static readonly string[] NonceStrings = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; /// /// 四舍五入取整数部分 /// /// /// public static int StringToIntMathRound(this object @this) { string s_this = @this.ToString(); int i_result = 0; if (s_this.Contains(".")) { var tS =s_this.Split("."); i_result = Convert.ToInt32(tS[0]); if (Convert.ToInt32(tS[1].Substring(0, 1)) > 4) { i_result += 1; } } else { i_result = Convert.ToInt32(@this); } return i_result; } /// /// 生成指定长度的随机字符串 /// /// public static string CreateNonceStr(this int stringLenght) { Random random = new Random(); var sb = new StringBuilder(); var length = NonceStrings.Length; for (int i = 0; i < stringLenght; i++) { //通过random获得的随机索引到,NonceStrings数组中获取对应数组值 sb.Append(NonceStrings[random.Next(length - 1)]); } return sb.ToString(); } /// /// 获取指定长度的随机数 /// /// public static string GetRandom(this string @prexString, int lenght) { string result = prexString; Random rd = new Random(); for (int i = 0; i < lenght - prexString.Length; i++) { int RandKey = rd.Next(100, 999); var index = RandKey % 10; result += numbers[index].ToString(); } return result; } /// /// decimal取指定位小数返回 /// /// /// /// public static decimal DecimalsFormat(this decimal @this,int decimals=2) { return Math.Round(@this, decimals); } /// /// 涉及到金额部分把最后的0 去掉 /// /// /// public static string CashFormat(this object @this) { string cashValue = @this.ToString(); if (cashValue != null && cashValue.Contains(".")) // { while (cashValue.EndsWith("0")) { cashValue = cashValue.Substring(0, cashValue.Length - 1); } if (cashValue.EndsWith(".")) cashValue = cashValue.Substring(0, cashValue.Length - 1); } return cashValue; } /// /// 判断是否为空 /// /// /// public static bool IsNullOrWhiteSpace(this string @this) { if (@this == null) return true; return string.IsNullOrWhiteSpace(@this.Trim()) || @this == "null"; } /// /// tostring的另一个版本,当是null字符串时返回空串 /// /// /// public static string ToSelfOrNullString(this string @this) { if (@this == null) return ""; return string.IsNullOrWhiteSpace(@this.Trim()) || @this == "null" ? "" : @this; } public static Hashtable GetProperties(this T @userInfo) { Hashtable hashtable = new Hashtable(); foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties()) { hashtable.Add(p.Name, p.GetValue(userInfo)); } return hashtable; } /// /// 去掉Emoji表情 /// /// /// public static string RemoveEmoji(this string @this) { foreach (var strTmp in @this) { byte[] bts = Encoding.UTF32.GetBytes(strTmp.ToString()); if (bts[0].ToString() == "253"&& bts[1].ToString() == "255") { @this = @this.Replace(strTmp.ToString(), ""); } } return @this; } /// /// 将Json字符串转换为对应的Json对象 /// /// /// /// public static T ToJsonObject(this string @this) { return JsonConvert.DeserializeObject(@this); } public static string DateTimeOfDayWeek(this string @this) { try { return ((int) Convert.ToDateTime(@this).DayOfWeek).ToString(); } catch (Exception e) { return ""; } } public static string YuanToFen(this string money) { return Convert.ToInt64(Convert.ToDecimal(money) * 100).ToString(); } public static string FenToYuan(this int money) { return (Convert.ToDecimal(money)/100).ToString(); } /// /// 将对象转换为string字符串 /// /// /// public static string ToJsonString(this object @this) { return JsonConvert.SerializeObject(@this); } /// /// 排序字段 /// /// /// public static Dictionary SortDictionary(this Dictionary @this) { Dictionary keyValues = new Dictionary(); foreach (var item in @this) { if (item.Value == null || item.Value.ToString() == "") { continue; } if(item.Key== "PatType") { } if (item.Value.GetType().Name == "JObject") { JObject j_object = item.Value as JObject; keyValues = keyValues.Concat(j_object.JObjectToDictionary()).ToDictionary(k => k.Key, v => v.Value); } else { keyValues.Add(item.Key, item.Value); } } return keyValues.OrderBy(p => p.Key).Where(d => d.Value != null).ToDictionary(p => p.Key, o => o.Value); } /// /// JObject to Dictionary /// /// /// private static Dictionary JObjectToDictionary(this JObject @this) { Dictionary keyValues = new Dictionary(); foreach (var item in @this) { keyValues.Add(item.Key, item.Value); //不考虑有多层的情况 //if (item.Value.GetType().Name == "JObject") //{ // JObject j_object = item.Value as JObject; // //还有子项目 // keyValues = keyValues.Concat(j_object.JObjectToDictionary()).ToDictionary(k => k.Key, v => v.Value); //} //else //{ // keyValues.Add(item.Key, item.Value); //} } return keyValues; } /// /// 转换成签名串 /// /// /// public static string ToSignString(this object @this) { var objName = @this.GetType().Name; if (objName == "DateTime") { return Convert.ToDateTime(@this).ToString("yyyy-MM-dd HH:mm:ss"); } else { return @this.ToString(); } } /// /// BASE64编码 /// /// /// /// public static string EncodeBase64(this string un_code_string,string code_type= "utf-8") { byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(un_code_string); string encode; try { encode = Convert.ToBase64String(bytes); } catch { encode = un_code_string; } return encode; } /// /// BASE64解码 /// /// /// /// public static string DecodeBase64(this string code_string,string code_type = "utf-8") { byte[] bytes = Convert.FromBase64String(code_string); string decode; try { decode = Encoding.GetEncoding(code_type).GetString(bytes); } catch { decode = code_string; } return decode; } /// /// xml格式的字符串转换成对象 /// /// /// public static T XmlToObject(this string xmlStr) where T : new() { try { T obj = new T(); var repType = typeof(T); XmlDocument document = new XmlDocument(); document.LoadXml(xmlStr); //加载Xml文件 XmlElement node = document.DocumentElement; //xml的根标签 var properties = repType.GetProperties(); foreach (var itemProp in properties) { #region current type is List if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List")) { object array = new object(); var arryLength = 0; var notNullLength = 0; var arryType = itemProp.PropertyType.UnderlyingSystemType; var objList = itemProp.GetValue(obj, null) as System.Collections.IEnumerable; var enumt = objList.GetEnumerator(); //enumt. var currentType = itemProp.PropertyType.GetGenericArguments()[0]; foreach (XmlNode xmlitem in node.ChildNodes) { if (xmlitem.Name == itemProp.Name) { arryLength++; } } if (arryLength > 0) { var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList; foreach (XmlNode item in node.ChildNodes) { //current type is array if (item.Name == itemProp.Name) { var model = currentType.Assembly.CreateInstance(currentType.FullName); // arryType.GetElementType().Assembly.CreateInstance(currentType.FullName); SetArray(item.ChildNodes, model, true); arrayModel.Add(model); //arrayModel[notNullLength] = model; notNullLength++; } } itemProp.SetValue(obj, arrayModel, null); } continue; } #endregion var baseType = itemProp.PropertyType.BaseType.Name; if (baseType == "Array") { #region Current type is Array object array = new object(); var arryLength = 0; var notNullLength = 0; var arryType = itemProp.PropertyType.UnderlyingSystemType; foreach (XmlNode xmlitem in node.ChildNodes) { if (xmlitem.Name == itemProp.Name && xmlitem.ChildNodes!=null && xmlitem.ChildNodes.Count>0) { arryLength++; } } if (arryLength > 0) { var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList; foreach (XmlNode item in node.ChildNodes) { //current type is array if (item.Name == itemProp.Name && item.ChildNodes!=null && item.ChildNodes.Count>0) { var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName); SetArray(item.ChildNodes, model); arrayModel[notNullLength] = model; notNullLength++; } } itemProp.SetValue(obj, arrayModel, null); } #endregion } else { #region Current type isn't Array foreach (XmlNode item in node.ChildNodes) { #region Current type is Number if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(string))) { if (itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(long)) { if (!string.IsNullOrEmpty(item.InnerText)) { if (itemProp.PropertyType == typeof(int)) { itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null); } else { itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null); } } else { itemProp.SetValue(obj, 0, null); } } else { itemProp.SetValue(obj, item.InnerText, null); } } #endregion #region Current type is Model if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element) { var modelType = itemProp.PropertyType.UnderlyingSystemType; var model = modelType.Assembly.CreateInstance(modelType.FullName); SetArray(item.ChildNodes, model); itemProp.SetValue(obj, model, null); } #endregion } #endregion } } repType = obj.GetType(); return obj; } catch (Exception ex) { throw ex; } } #region Set array value private static Object SetArray(XmlNodeList xmlNodeList, object obj, bool isList = false) { try { var type = obj.GetType(); var properties = type.GetProperties(); foreach (var itemProp in properties) { //if (isList) if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List")) { #region Current type is List object array = new object(); var arryLength = 0; var notNullLength = 0; var arryType = itemProp.PropertyType.UnderlyingSystemType; var currentType = itemProp.PropertyType.GetGenericArguments()[0]; foreach (XmlNode xmlitem in xmlNodeList) { if (xmlitem.Name == itemProp.Name) { arryLength++; } } if (arryLength > 0) { var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList; foreach (XmlNode item in xmlNodeList) { //current type is array if (item.Name == itemProp.Name) { var model = currentType.Assembly.CreateInstance(currentType.FullName); // var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName); SetArray(item.ChildNodes, model, true); arrayModel.Add(model); notNullLength++; } } itemProp.SetValue(obj, arrayModel, null); } #endregion return obj; } var baseType = itemProp.PropertyType.BaseType.Name; if (baseType == "Array") { #region Current type is Array object array = new object(); var arryLength = 0; var notNullLength = 0; var arryType = itemProp.PropertyType.UnderlyingSystemType; foreach (XmlNode xmlitem in xmlNodeList) { if (xmlitem.Name == itemProp.Name) { arryLength++; } } if (arryLength > 0) { var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList; foreach (XmlNode item in xmlNodeList) { //current type is array if (item.Name == itemProp.Name) { var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName); SetArray(item.ChildNodes, model); arrayModel[notNullLength] = model; notNullLength++; } } itemProp.SetValue(obj, arrayModel, null); } #endregion } else { foreach (XmlNode item in xmlNodeList) { #region Current type is Number if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(string))) { if (itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(long)) { if (!string.IsNullOrEmpty(item.InnerText)) { if (itemProp.PropertyType == typeof(int)) { itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null); } else { itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null); } } else { itemProp.SetValue(obj, 0, null); } } else { itemProp.SetValue(obj, item.InnerText, null); } } #endregion #region Current type is Model if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element) { var modelType = itemProp.PropertyType.UnderlyingSystemType; var model = modelType.Assembly.CreateInstance(modelType.FullName); SetArray(item.ChildNodes, model); itemProp.SetValue(obj, model, null); } #endregion } } } } catch (Exception ex) { throw new Exception(ex.Message); } return obj; } #endregion } }