123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 |
- using System;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Text.Encodings.Web;
- using System.Text.Json;
- using System.Text.Json.Serialization;
- using System.Text.Unicode;
- namespace DPP_YH_Core.Extensions
- {
- public static class ObjectExtension
- {
- private class DateTimeConverter : JsonConverter<DateTime>
- {
- public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
- {
- return DateTime.Parse(reader.GetString());
- }
- public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
- {
- writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
- }
- }
- /// <summary>
- /// <para>对象转JsonString</para>
- /// <para>如果对象本身是String类型则直接返回</para>
- /// </summary>
- /// <param name="obj">对象</param>
- /// <param name="formarting">是否开启格式化,格式化会多占用一些字节,默认不格式化</param>
- /// <returns></returns>
- public static string ToJsonStr(this object obj, bool formarting = false)
- {
- if (obj == null) return "";
- if (obj.GetType() == typeof(string)) return obj as string;
- if (obj.GetType() == typeof(StringBuilder)) return ((StringBuilder)obj).ToString();
- var options = new JsonSerializerOptions
- {
- WriteIndented = formarting,
- IncludeFields = true,
- DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
- };
- options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
- //不加这句非ASCII字符会被序列化为Unicode编号,类似于\u8C03
- options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
- options.GetConverter(obj.GetType());
- var res = JsonSerializer.Serialize(obj, options);
- return res;
- }
- public static string ToNewtonJsonStr(this object obj)
- {
- return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
- }
- public static T ToJson<T>(this string obj)
- {
- return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(obj);
- }
- public static T To<T>(this Object @this)
- {
- if (@this != null)
- {
- Type targetType = typeof(T);
- if (@this.GetType() == targetType)
- {
- return (T)@this;
- }
- TypeConverter converter = TypeDescriptor.GetConverter(@this);
- if (converter != null)
- {
- if (converter.CanConvertTo(targetType))
- {
- return (T)converter.ConvertTo(@this, targetType);
- }
- }
- converter = TypeDescriptor.GetConverter(targetType);
- if (converter != null)
- {
- if (converter.CanConvertFrom(@this.GetType()))
- {
- return (T)converter.ConvertFrom(@this);
- }
- }
- if (@this == DBNull.Value)
- {
- return (T)(object)null;
- }
- }
- return (T)@this;
- }
- public static object To(this Object @this, Type type)
- {
- if (@this != null)
- {
- Type targetType = type;
- if (@this.GetType() == targetType)
- {
- return @this;
- }
- TypeConverter converter = TypeDescriptor.GetConverter(@this);
- if (converter != null)
- {
- if (converter.CanConvertTo(targetType))
- {
- return converter.ConvertTo(@this, targetType);
- }
- }
- converter = TypeDescriptor.GetConverter(targetType);
- if (converter != null)
- {
- if (converter.CanConvertFrom(@this.GetType()))
- {
- return converter.ConvertFrom(@this);
- }
- }
- if (@this == DBNull.Value)
- {
- return null;
- }
- }
- return @this;
- }
- /// <summary>
- /// <para>将源对象的属性值映射到target对象上,(target==null时直接返回)</para>
- /// <para>该方法使用反射</para>
- /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
- /// </summary>
- /// <typeparam name="T">target泛型类</typeparam>
- /// <param name="obj">源对象</param>
- /// <param name="target">目标对象</param>
- public static void MapTo<T>(this object obj, T target) where T : class, new()
- {
- if (obj == null || target == null) return;
- var objProps = obj.GetType().GetProperties();
- if (objProps == null || objProps.Length == 0) return;
- var listObjProps = objProps.ToList();
- //var str = JsonConvert.SerializeObject(obj);
- //var foo = JsonConvert.DeserializeObject<T>(str);
- var props = typeof(T).GetProperties();
- foreach (var item in props)
- {
- if (!item.CanWrite) continue;
- var find = listObjProps.Find(p => p.Name == item.Name);
- if (find == null) continue;
- var value = find.GetValue(obj);
- if (value == null) continue;
- if (item.PropertyType != value.GetType() && !item.PropertyType.Name.Contains("Nullable"))
- {
- value = Convert.ChangeType(value, item.PropertyType);
- }
- item.SetValue(target, value);
- }
- }
- /// <summary>
- /// <para>将源对象的映射为一个新对象</para>
- /// <para>该方法使用json序列化,对象嵌套深度不能超过8层</para>
- /// <para>源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2</para>
- /// </summary>
- /// <typeparam name="T">返回对象泛型类型</typeparam>
- /// <param name="obj">源对象</param>
- /// <returns></returns>
- public static T MapTo<T>(this object obj)
- {
- string str;
- JsonSerializerOptions options = null;
- if (obj == null)
- str = "";
- else if (obj.GetType() == typeof(string))
- str = obj.ToString();
- else if (obj.GetType() == typeof(StringBuilder))
- str = ((StringBuilder)obj).ToString();
- else
- {
- options = new JsonSerializerOptions
- {
- WriteIndented = false,
- IncludeFields = true,
- DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
- };
- options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
- options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
- str = JsonSerializer.Serialize(obj, options);
- }
- if (options == null)
- {
- options = new JsonSerializerOptions
- {
- WriteIndented = false,
- IncludeFields = true,
- DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
- };
- options.Converters.Add(new DateTimeConverter());//yyyy-MM-dd HH:mm:ss
- options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
- }
- if (string.IsNullOrWhiteSpace(str)) return default;
- var res = JsonSerializer.Deserialize<T>(str, options);
- return res;
- }
- //public static T MapTo<T>(this object obj) where T: class,new()
- //{
- // if (obj == null) return null;
- // var objProps = obj.GetType().GetProperties();
- // if (objProps == null || objProps.Length == 0) return null;
- // T t = new T();
- // obj.MapTo(t);
- // return t;
- //}
- }
- }
|