ObjectExtends.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.Encodings.Web;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization;
  8. using System.Text.Unicode;
  9. using System.Threading.Tasks;
  10. public static class ObjectExtends
  11. {
  12. private class DateTimeConverter : JsonConverter<DateTime>
  13. {
  14. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. return DateTime.Parse(reader.GetString());
  17. }
  18. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  19. {
  20. writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
  21. }
  22. }
  23. /// <summary>
  24. /// 判断obj是否是数字
  25. /// <para>bool也算数字</para>
  26. /// <para>null返回false</para>
  27. /// </summary>
  28. /// <param name="o"></param>
  29. /// <returns></returns>
  30. public static bool IsNumericType(this Type t)
  31. {
  32. //常用类型放前面提高效率
  33. if (t == null) return false;
  34. if (t == typeof(string) || t == typeof(DateTime)) return false;
  35. if (t == typeof(int)) return true;
  36. if (t == typeof(double)) return true;
  37. if (t == typeof(float)) return true;
  38. if (t == typeof(long)) return true;
  39. if (t == typeof(bool)) return true;
  40. if (t == typeof(byte)) return true;
  41. if (t == typeof(sbyte)) return true;
  42. if (t == typeof(ushort)) return true;
  43. if (t == typeof(uint)) return true;
  44. if (t == typeof(ulong)) return true;
  45. if (t == typeof(short)) return true;
  46. if (t == typeof(decimal)) return true;
  47. return false;
  48. }
  49. /// <summary>
  50. /// 判断obj是否是非整数类型
  51. /// <para>包含float、double、decimal</para>
  52. /// <para>null返回false</para>
  53. /// </summary>
  54. /// <param name="o"></param>
  55. /// <returns></returns>
  56. public static bool IsFloatType(this Type t)
  57. {
  58. if (t == null) return false;
  59. if (t == typeof(double)) return true;
  60. if (t == typeof(float)) return true;
  61. if (t == typeof(decimal)) return true;
  62. return false;
  63. }
  64. /// <summary>
  65. /// <para>将源对象的属性值映射到target对象上,(target==null时直接返回)</para>
  66. /// <para>该方法使用反射</para>
  67. /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
  68. /// </summary>
  69. /// <typeparam name="T">target泛型类</typeparam>
  70. /// <param name="obj">源对象</param>
  71. /// <param name="target">目标对象</param>
  72. public static void MapTo<T>(this object obj, T target)
  73. {
  74. if (obj == null || target == null) return;
  75. var objProps = obj.GetType().GetProperties();
  76. if (objProps == null || objProps.Length == 0) return;
  77. var listObjProps = objProps.ToList();
  78. //var str = JsonConvert.SerializeObject(obj);
  79. //var foo = JsonConvert.DeserializeObject<T>(str);
  80. var props = typeof(T).GetProperties();
  81. foreach (var item in props)
  82. {
  83. if (!item.CanWrite) continue;
  84. var find = listObjProps.Find(p => p.Name == item.Name);
  85. if (find == null) continue;
  86. var value = find.GetValue(obj);
  87. if (value == null) continue;
  88. ;
  89. if (item.PropertyType != value.GetType() && !item.PropertyType.Name.Contains("Nullable"))
  90. {
  91. value = Convert.ChangeType(value, item.PropertyType);
  92. }
  93. item.SetValue(target, value);
  94. }
  95. }
  96. /// <summary>
  97. /// <para>将源对象的映射为一个新对象</para>
  98. /// <para>该方法使用json序列化,对象嵌套深度不能超过8层</para>
  99. /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
  100. /// </summary>
  101. /// <typeparam name="T">返回对象泛型类型</typeparam>
  102. /// <param name="obj">源对象</param>
  103. /// <returns></returns>
  104. public static T MapTo<T>(this object obj)
  105. {
  106. string str;
  107. JsonSerializerOptions options = null;
  108. if (obj == null)
  109. str = "";
  110. else if (obj.GetType() == typeof(string))
  111. str = obj.ToString();
  112. else if (obj.GetType() == typeof(StringBuilder))
  113. str = ((StringBuilder)obj).ToString();
  114. else
  115. {
  116. options = new JsonSerializerOptions();
  117. options.WriteIndented = false;
  118. options.IncludeFields = true;
  119. options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  120. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  121. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  122. str = JsonSerializer.Serialize(obj, options);
  123. }
  124. if (options == null)
  125. {
  126. options = new JsonSerializerOptions();
  127. options.WriteIndented = false;
  128. options.IncludeFields = true;
  129. options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  130. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  131. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  132. }
  133. if (string.IsNullOrWhiteSpace(str)) return default;
  134. var res = JsonSerializer.Deserialize<T>(str, options);
  135. return res;
  136. }
  137. /// <summary>
  138. /// <para>对象转JsonString</para>
  139. /// <para>如果对象本身是String类型则直接返回</para>
  140. /// </summary>
  141. /// <param name="obj">对象</param>
  142. /// <param name="formarting">是否开启格式化,格式化会多占用一些字节,默认不格式化</param>
  143. /// <returns></returns>
  144. public static string ToJsonStr(this object obj, bool formarting = false)
  145. {
  146. if (obj == null) return "";
  147. if (obj.GetType() == typeof(string)) return obj as string;
  148. if (obj.GetType() == typeof(StringBuilder)) return ((StringBuilder)obj).ToString();
  149. var options = new JsonSerializerOptions();
  150. options.WriteIndented = formarting;
  151. options.IncludeFields = true;
  152. options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
  153. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  154. //不加这句非ASCII字符会被序列化为Unicode编号,类似于\u8C03
  155. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  156. var res = JsonSerializer.Serialize(obj, options);
  157. return res;
  158. }
  159. }