//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // API首页:https://www.yuque.com/rrqm/touchsocket/index // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Dynamic; using System.Linq; using System.Reflection; using System.Text; namespace TouchSocket.Core { /// /// Json高速转换 /// 此代码来源:https://gitee.com/majorworld /// public static class JsonFastConverter { /// /// 全局时间序列化样式,默认为yyyy-MM-dd HH:mm:ss /// public static string TimeFormat = "yyyy-MM-dd HH:mm:ss"; /// /// 将Json字符串转为指定类型 /// /// /// /// public static T JsonFrom(string s) where T : class { return (T)JsonFrom(s, typeof(T)); } /// /// 将Json字符串转为指定类型 /// /// /// /// /// public static object JsonFrom(string s, Type t) { if (s == null) throw new NullReferenceException("不能为null"); StringBuilder sb = new StringBuilder(s.Length); Dictionary dict = new Dictionary(); List list = new List(); int index = 0; switch (s[0]) { case '{': return s.GetObject(ref index, sb, list).ToObject(t); case '[': var data = s.GetArray(ref index, sb, dict); if (t == typeof(DataTable)) return data.ToDataTable();//处理表类型 if (t.GetGenericArguments().Length < 1) { if (t.IsArray) JsonChange.ChangeArray(t.GetElementType(), data);//处理数组类型 return JsonChange.ChangeData(t, data);//处理动态类型 } if (t.IsList()) { return JsonChange.ChangeList(t.GetGenericArguments()[0], data);//处理集合类型 } throw new NullReferenceException("类型应该为集合或数组或dynamic"); default: throw new NullReferenceException("第一个字符缺失{或["); } } /// /// 将Json字符串转为对象
/// 重载,当前数据类型速度最快 ///
/// /// public static Dictionary JsonFrom(string s) { return JsonFrom>(s); } /// /// 将对象转为Json字符串 /// /// /// /// 时间序列化样式,默认为yyyy-MM-dd HH:mm:ss /// public static string JsonTo(T t, string timeFormat = null) { StringBuilder sb = new StringBuilder(); t.CodeObject(sb, timeFormat ?? TimeFormat); return sb.ToString(); } } /// /// 过滤不需要序列化的字段 /// public class JsonFastIgnore : Attribute { } /// /// 转换为实体类对应的类型 /// internal static class JsonChange { #region 类型判断 internal static bool IsDictionary(this Type type) => (typeof(IDictionary).IsAssignableFrom(type)); internal static bool IsList(this Type type) => (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)); #endregion 类型判断 #region 转换 /// /// 处理数组类型 /// https://gitee.com/majorworld /// /// /// /// internal static object ChangeArray(Type type, IList data) { var array = Array.CreateInstance(type, data.Count); for (int i = 0; i < data.Count; i++) { array.SetValue(type.ChangeData(data[i]), i); } return array; } /// /// 转换ArrayList类型 /// https://gitee.com/majorworld /// /// /// internal static ArrayList ChangeArrayList(object value) { ArrayList array = new ArrayList(); if (value is IList list) { foreach (var item in list) array.Add(item); } return array; } /// /// 转换为各种数据 /// https://gitee.com/majorworld /// /// /// /// internal static object ChangeData(this Type p, object value) { if (value is Dictionary dictionary) { return ToObject(dictionary, p);//解析子级实体类的数据 } else if (p == typeof(string)) { return Convert.ChangeType(value, p); } else if (p.IsPrimitive && p != typeof(char)) { return Convert.ChangeType(value, p); } else if (p == typeof(byte[])) { return Convert.FromBase64String(value as string); } else if (p == typeof(Guid)) { return Guid.Parse(value as string); } else if (p == typeof(ArrayList)) { return ChangeArrayList(value);//处理动态数组类型 } else if (value is IList list) { if (p.GetGenericArguments().Length < 1) { if (p.IsArray) return ChangeArray(p.GetElementType(), value as IList);//处理数组类型 List d = new List(); foreach (var kv in list as dynamic) { if (kv is Dictionary dict) d.Add(dict.ToObject(typeof(object))); } return d;//解析dynamic } return ChangeList(p.GetGenericArguments()[0], value as List);//处理List类型 } return Convert.ChangeType(value, p); } /// /// 处理字典类型 /// https://gitee.com/majorworld /// /// /// /// internal static object ChangeDictionary(Type type, Dictionary dict) { //反射创建泛型字典 var t = typeof(Dictionary<,>).MakeGenericType(new[] { type.GetGenericArguments()[0], type.GetGenericArguments()[1] }); ; var d = Activator.CreateInstance(t) as IDictionary; foreach (var item in dict) d.Add(type.GetGenericArguments()[0].ChangeData(item.Key), type.GetGenericArguments()[1].ChangeData(item.Value)); return d; } /// /// 处理集合类型 /// https://gitee.com/majorworld /// /// /// /// internal static object ChangeList(Type type, List data) { IList list = Activator.CreateInstance(typeof(List<>).MakeGenericType(type)) as IList; foreach (var item in data) list.Add(type.ChangeData(item)); return list; } /// /// List转DataTable /// https://gitee.com/majorworld /// /// /// /// internal static DataTable ToDataTable(this List list) { DataTable dt = new DataTable(); for (int i = 0; i < list.Count; i++) { Dictionary dict = list[i] as Dictionary; if (i == 0) { foreach (var item in dict) { dt.Columns.Add(item.Key, item.Value.GetType()); } } dt.Rows.Add(dict.Values.ToArray()); } return dt; } /// /// 转换为对象 /// https://gitee.com/majorworld /// /// /// /// internal static object ToObject(this Dictionary dict, Type type) { //(1/4)返回原始解析数据 if (type == typeof(Dictionary)) { return dict; } //(2/4)返回dynamic类型数据 if (type.UnderlyingSystemType.Name == "Object") { dynamic d = new ExpandoObject(); foreach (var kv in dict) { if (kv.Value is Dictionary dictionary) (d as ICollection>).Add(new KeyValuePair(kv.Key, ToObject(dictionary, typeof(object)))); else (d as ICollection>).Add(kv); } return d; } //(3/4)返回DataSet类型数据 if (type == typeof(DataSet)) { DataSet ds = new DataSet(); foreach (var item in dict) { if (item.Value is List list) { var dt = list.ToDataTable(); dt.TableName = item.Key; ds.Tables.Add(dt); } } return ds; } //(4/4)返回所绑定的实体类数据 var obj = Activator.CreateInstance(type); var props = type.GetCacheInfo(); foreach (var kv in dict) { var prop = props.Where(x => string.Equals(x.Name, kv.Key, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (prop is null) { if (type.IsDictionary()) { return ChangeDictionary(type, dict);//解析值是字典的数据(非缓存字段的字典) } continue; } if (prop.CanWrite) { prop.SetValue(obj, prop.PropertyType.ChangeData(kv.Value), null);//递归调用当前方法,解析子级 } } return obj; } private static object Go(string sValue) { Type type = typeof(T); return System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(sValue.ToString()); } #endregion 转换 } /// /// 解析字符串为对象 /// internal static class JsonDecode { #region 解析 /// /// 解析集合 /// https://gitee.com/majorworld /// /// /// /// /// /// internal static List GetArray(this string s, ref int index, StringBuilder sb, Dictionary dict) { index++; List list = new List(); while (index < s.Length) { switch (s[index]) { case ',': index++; break; case '"': list.Add(s.GetString(ref index, sb)); break; case ']': ++index; return list; case ' ': case '\r': case '\n': case '\t': case '\f': case '\b': ++index; break; default: list.Add(s.GetData(s[index], ref index, sb, dict, list)); break; } } return list; } /// /// 解析对象 /// https://gitee.com/majorworld /// /// /// /// /// /// internal static Dictionary GetObject(this string s, ref int index, StringBuilder sb, List list) { index++; Dictionary dict = new Dictionary(); string key = string.Empty; bool iskey = true; while (index < s.Length) { switch (s[index]) { case ',': iskey = true; key = string.Empty; index++; break; case ':': iskey = false; index++; break; case '}': ++index; return dict; case '"': if (iskey) key = s.GetString(ref index, sb); else dict.Add(key, s.GetString(ref index, sb)); break; case ' ': case '\r': case '\n': case '\t': case '\f': case '\b': index++; break; default: dict.Add(key, s.GetData(s[index], ref index, sb, dict, list)); break; } } throw new FormatException("解析错误,不完整的Json"); } /// /// 获取布尔数据 /// https://gitee.com/majorworld /// /// /// /// /// private static bool GetBool(this string s, ref int index, bool state) { if (state) { if (s[index + 1] == 'r' && s[index + 2] == 'u' && s[index + 3] == 'e') { index += 4; return true; } } else { if (s[index + 1] == 'a' && s[index + 2] == 'l' && s[index + 3] == 's' && s[index + 4] == 'e') { index += 5; return false; } } throw new FormatException($"\"{string.Concat(s[index], s[index + 1], s[index + 2], s[index + 3])}\"处Json格式无法解析"); } /// /// 自动获取数据 /// https://gitee.com/majorworld /// /// /// /// /// /// /// /// private static object GetData(this string s, char c, ref int index, StringBuilder sb, Dictionary dict, List list) { switch (c) { case 't': return s.GetBool(ref index, true); case 'f': return s.GetBool(ref index, false); case 'n': return s.GetNull(ref index); case '{': return s.GetObject(ref index, sb, list); case '[': return s.GetArray(ref index, sb, dict); default: return s.GetNumber(ref index, sb); } } /// /// 获取空数据 /// https://gitee.com/majorworld /// /// /// /// private static object GetNull(this string s, ref int index) { if (s[index + 1] == 'u' && s[index + 2] == 'l' && s[index + 3] == 'l') { index += 4; return null; } throw new FormatException($"\"{string.Concat(s[index], s[index + 1], s[index + 2], s[index + 3])}\"处Json格式无法解析"); } /// /// 获取数字数据 /// https://gitee.com/majorworld /// /// /// /// /// private static object GetNumber(this string s, ref int index, StringBuilder sb) { sb.Clear(); for (; index < s.Length; ++index) { if (s[index] == ',' || s[index] == '}' || s[index] == ']' || s[index] == ' ' || s[index] == '\n' || s[index] == '\r') break; else sb.Append(s[index]); } string code = sb.ToString(); if (long.TryParse(code, out long x)) return x; if (double.TryParse(code, out double y)) return y; throw new FormatException($"\"{code}\"处Json格式无法解析"); } /// /// 获取字符串数据 /// https://gitee.com/majorworld /// /// /// /// /// private static string GetString(this string s, ref int index, StringBuilder sb) { sb.Clear(); index++; for (; index < s.Length; ++index) { switch (s[index]) { case '"': index++; return sb.ToString(); case '\\': if (s[index + 1] == '"' || s[index + 1] == '\\') index++; sb.Append(s[index]); break; default: sb.Append(s[index]); break; } } throw new FormatException($"\"{sb}\"处Json格式无法解析"); } #endregion 解析 } /// /// 编码对象为字符串 /// internal static class JsonEncode { /// /// 缓存数据加速序列化速度,主要是减少不必要的GetCustomAttributes获取特性并过滤字段 /// internal static ConcurrentDictionary InfoCache = new ConcurrentDictionary(); /// /// 序列化 /// /// /// /// internal static void CodeObject(this object obj, StringBuilder sb, string timeFormat) { bool get = true; switch (obj) { case null: sb.Append("null"); break; case Enum _: sb.Append($"{Convert.ToInt32(obj)}"); break; case byte[] bytes: sb.Append($"\"{Convert.ToBase64String(bytes)}\""); break; case Array array: sb.Append('['); for (int i = 0; i < array.Length; i++) { if (i != 0) sb.Append(","); array.GetValue(i).CodeObject(sb, timeFormat); } sb.Append(']'); break; case string _: sb.Append($"\"{obj}\""); break; case char _: sb.Append($"\"{obj}\""); break; case bool _: sb.Append($"{obj.ToString().ToLower()}"); break; case DataTable dt: dt.CodeDataTable(sb, timeFormat); break; case DataSet ds: sb.Append('{'); for (int i = 0; i < ds.Tables.Count; i++) { if (i != 0) sb.Append(","); sb.Append($"\"{ds.Tables[i].TableName}\":"); ds.Tables[i].CodeDataTable(sb, timeFormat); } sb.Append('}'); break; case DateTime time: sb.AppendFormat($"\"{time.ToString(timeFormat)}\""); break; case Guid id: sb.AppendFormat($"\"{id}\""); break; case ArrayList list: sb.Append('['); for (int i = 0; i < list.Count; i++) { if (i != 0) sb.Append(","); list[i].CodeObject(sb, timeFormat); } sb.Append(']'); break; default: get = false; break; } if (get) return; Type type = obj.GetType(); //数字 if (type.IsPrimitive && type != typeof(char)) { sb.Append($"{obj}"); return; } //字典 else if (type.IsDictionary()) { sb.Append('{'); var collection = obj as IDictionary; var enumerator = collection.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { if (index != 0) sb.Append(","); sb.Append($"\"{enumerator.Key}\":"); enumerator.Value.CodeObject(sb, timeFormat); index++; } sb.Append('}'); return; } //集合 else if (type.IsList()) { sb.Append('['); if (obj is IList list) { for (int i = 0; i < list.Count; i++) { if (i != 0) sb.Append(","); list[i].CodeObject(sb, timeFormat); } } sb.Append(']'); return; } else if (type.UnderlyingSystemType.Name == "ExpandoObject") { sb.Append('{'); bool first = true; foreach (dynamic item in obj as dynamic) { if (!first) sb.Append(','); first = false; object value = item.Value; sb.Append($"\"{item.Key}\":"); value.CodeObject(sb, timeFormat); } sb.Append('}'); return; } //对象 var prop = type.GetCacheInfo(); if (prop is null) { sb.Append("null"); return; } sb.Append('{'); for (int i = 0; i < prop.Length; i++) { PropertyInfo p = prop[i]; if (i != 0) sb.Append(","); var data = p.GetValue(obj, null); sb.Append($"\"{p.Name}\":"); data.CodeObject(sb, timeFormat); } sb.Append("}"); } /// /// 尝试获取缓存中的类型,排除忽略的字段 /// /// /// internal static PropertyInfo[] GetCacheInfo(this Type type) { if (InfoCache.TryGetValue(type, out PropertyInfo[] props)) { } else { props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); List cache = new List(); foreach (var item in props) { if (Attribute.GetCustomAttributes(item, typeof(JsonFastIgnore))?.Length == 0) cache.Add(item); } InfoCache[type] = cache.ToArray(); props = cache.ToArray(); } return props; } /// /// 序列化DataTable /// /// /// /// 时间格式化样式,默认为yyyy-MM-dd HH:mm:ss private static void CodeDataTable(this DataTable dt, StringBuilder sb, string timeFormat) { sb.Append('['); for (int i = 0; i < dt.Rows.Count; i++) { if (i != 0) sb.Append(","); var item = dt.Rows[i]; sb.Append('{'); for (int j = 0; j < dt.Columns.Count; j++) { if (j != 0) sb.Append(","); var cell = dt.Columns[j]; sb.Append($"\"{cell}\":"); item[j].CodeObject(sb, timeFormat); } sb.Append('}'); } sb.Append(']'); } } }