using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Reflection; namespace IRaCIS.Core.Infrastructure.Extention { public static class ObjectExtension { public static T Clone(this T source) { // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; var serializeSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(source, serializeSettings), deserializeSettings); } /// /// 将对象序列化成稽查需要的Json字符串 /// /// /// public static string ToJsonStr(this object obj) { return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss", ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }); } /// /// 将对象序列化成稽查需要的Json字符串 /// /// /// public static string ToJsonNotIgnoreNull(this object obj) { return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { DateFormatString = "yyyy-MM-dd HH:mm:ss", Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Include }); } public static Dictionary ConvertToDictionary(this object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(); Dictionary dictionary = new Dictionary(); foreach (PropertyInfo property in properties) { string propertyName = property.Name; object propertyValue = property.GetValue(obj); // 如果属性的类型是枚举,将其值保留为整数 if (property.PropertyType.IsEnum) { dictionary.Add(propertyName, (int)propertyValue); } else { dictionary.Add(propertyName, propertyValue); } } return dictionary; } } }