ObjectExtension.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using System;
  2. using System.ComponentModel;
  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. namespace DPP_YH_Core.Extensions
  10. {
  11. public static class ObjectExtension
  12. {
  13. private class DateTimeConverter : JsonConverter<DateTime>
  14. {
  15. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  16. {
  17. return DateTime.Parse(reader.GetString());
  18. }
  19. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  20. {
  21. writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
  22. }
  23. }
  24. /// <summary>
  25. /// <para>对象转JsonString</para>
  26. /// <para>如果对象本身是String类型则直接返回</para>
  27. /// </summary>
  28. /// <param name="obj">对象</param>
  29. /// <param name="formarting">是否开启格式化,格式化会多占用一些字节,默认不格式化</param>
  30. /// <returns></returns>
  31. public static string ToJsonStr(this object obj, bool formarting = false)
  32. {
  33. if (obj == null) return "";
  34. if (obj.GetType() == typeof(string)) return obj as string;
  35. if (obj.GetType() == typeof(StringBuilder)) return ((StringBuilder)obj).ToString();
  36. var options = new JsonSerializerOptions
  37. {
  38. WriteIndented = formarting,
  39. IncludeFields = true,
  40. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
  41. };
  42. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  43. //不加这句非ASCII字符会被序列化为Unicode编号,类似于\u8C03
  44. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  45. options.GetConverter(obj.GetType());
  46. var res = JsonSerializer.Serialize(obj, options);
  47. return res;
  48. }
  49. public static string ToNewtonJsonStr(this object obj)
  50. {
  51. return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  52. }
  53. public static T ToJson<T>(this string obj)
  54. {
  55. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(obj);
  56. }
  57. public static T To<T>(this Object @this)
  58. {
  59. if (@this != null)
  60. {
  61. Type targetType = typeof(T);
  62. if (@this.GetType() == targetType)
  63. {
  64. return (T)@this;
  65. }
  66. TypeConverter converter = TypeDescriptor.GetConverter(@this);
  67. if (converter != null)
  68. {
  69. if (converter.CanConvertTo(targetType))
  70. {
  71. return (T)converter.ConvertTo(@this, targetType);
  72. }
  73. }
  74. converter = TypeDescriptor.GetConverter(targetType);
  75. if (converter != null)
  76. {
  77. if (converter.CanConvertFrom(@this.GetType()))
  78. {
  79. return (T)converter.ConvertFrom(@this);
  80. }
  81. }
  82. if (@this == DBNull.Value)
  83. {
  84. return (T)(object)null;
  85. }
  86. }
  87. return (T)@this;
  88. }
  89. public static object To(this Object @this, Type type)
  90. {
  91. if (@this != null)
  92. {
  93. Type targetType = type;
  94. if (@this.GetType() == targetType)
  95. {
  96. return @this;
  97. }
  98. TypeConverter converter = TypeDescriptor.GetConverter(@this);
  99. if (converter != null)
  100. {
  101. if (converter.CanConvertTo(targetType))
  102. {
  103. return converter.ConvertTo(@this, targetType);
  104. }
  105. }
  106. converter = TypeDescriptor.GetConverter(targetType);
  107. if (converter != null)
  108. {
  109. if (converter.CanConvertFrom(@this.GetType()))
  110. {
  111. return converter.ConvertFrom(@this);
  112. }
  113. }
  114. if (@this == DBNull.Value)
  115. {
  116. return null;
  117. }
  118. }
  119. return @this;
  120. }
  121. /// <summary>
  122. /// <para>将源对象的属性值映射到target对象上,(target==null时直接返回)</para>
  123. /// <para>该方法使用反射</para>
  124. /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
  125. /// </summary>
  126. /// <typeparam name="T">target泛型类</typeparam>
  127. /// <param name="obj">源对象</param>
  128. /// <param name="target">目标对象</param>
  129. public static void MapTo<T>(this object obj, T target) where T : class, new()
  130. {
  131. if (obj == null || target == null) return;
  132. var objProps = obj.GetType().GetProperties();
  133. if (objProps == null || objProps.Length == 0) return;
  134. var listObjProps = objProps.ToList();
  135. //var str = JsonConvert.SerializeObject(obj);
  136. //var foo = JsonConvert.DeserializeObject<T>(str);
  137. var props = typeof(T).GetProperties();
  138. foreach (var item in props)
  139. {
  140. if (!item.CanWrite) continue;
  141. var find = listObjProps.Find(p => p.Name == item.Name);
  142. if (find == null) continue;
  143. var value = find.GetValue(obj);
  144. if (value == null) continue;
  145. if (item.PropertyType != value.GetType() && !item.PropertyType.Name.Contains("Nullable"))
  146. {
  147. value = Convert.ChangeType(value, item.PropertyType);
  148. }
  149. item.SetValue(target, value);
  150. }
  151. }
  152. /// <summary>
  153. /// <para>将源对象的映射为一个新对象</para>
  154. /// <para>该方法使用json序列化,对象嵌套深度不能超过8层</para>
  155. /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
  156. /// </summary>
  157. /// <typeparam name="T">返回对象泛型类型</typeparam>
  158. /// <param name="obj">源对象</param>
  159. /// <returns></returns>
  160. public static T MapTo<T>(this object obj)
  161. {
  162. string str;
  163. JsonSerializerOptions options = null;
  164. if (obj == null)
  165. str = "";
  166. else if (obj.GetType() == typeof(string))
  167. str = obj.ToString();
  168. else if (obj.GetType() == typeof(StringBuilder))
  169. str = ((StringBuilder)obj).ToString();
  170. else
  171. {
  172. options = new JsonSerializerOptions
  173. {
  174. WriteIndented = false,
  175. IncludeFields = true,
  176. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
  177. };
  178. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  179. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  180. str = JsonSerializer.Serialize(obj, options);
  181. }
  182. if (options == null)
  183. {
  184. options = new JsonSerializerOptions
  185. {
  186. WriteIndented = false,
  187. IncludeFields = true,
  188. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
  189. };
  190. options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
  191. options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  192. }
  193. if (string.IsNullOrWhiteSpace(str)) return default;
  194. var res = JsonSerializer.Deserialize<T>(str, options);
  195. return res;
  196. }
  197. //public static T MapTo<T>(this object obj) where T: class,new()
  198. //{
  199. // if (obj == null) return null;
  200. // var objProps = obj.GetType().GetProperties();
  201. // if (objProps == null || objProps.Length == 0) return null;
  202. // T t = new T();
  203. // obj.MapTo(t);
  204. // return t;
  205. //}
  206. }
  207. }