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 { 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")); } } /// /// 对象转JsonString /// 如果对象本身是String类型则直接返回 /// /// 对象 /// 是否开启格式化,格式化会多占用一些字节,默认不格式化 /// 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(this string obj) { return Newtonsoft.Json.JsonConvert.DeserializeObject(obj); } public static T To(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; } /// /// 将源对象的属性值映射到target对象上,(target==null时直接返回) /// 该方法使用反射 /// 源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2 /// /// target泛型类 /// 源对象 /// 目标对象 public static void MapTo(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(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); } } /// /// 将源对象的映射为一个新对象 /// 该方法使用json序列化,对象嵌套深度不能超过8层 /// 源对象和目标对象可以是不同对象,只要属性名称一致即可,如Model1映射到Model2 /// /// 返回对象泛型类型 /// 源对象 /// public static T MapTo(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(str, options); return res; } //public static T MapTo(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; //} } }