using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; namespace WCS_Client { /// /// 扩展.json序列反序列化 /// public static partial class JsonExtensions { /// /// 转成json对象 /// /// json字串 /// public static object ToJson(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject(Json); } /// /// 转成json字串 /// /// 对象 /// public static string ToJson(this object obj) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; return JsonConvert.SerializeObject(obj, timeConverter); } /// /// 转成json字串 /// /// 对象 /// 时间格式化 /// public static string ToJson(this object obj, string datetimeformats) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats }; return JsonConvert.SerializeObject(obj, timeConverter); } /// /// 字串反序列化成指定对象实体 /// /// 实体类型 /// 字串 /// public static T ToObject(this string Json) { return Json == null ? default(T) : JsonConvert.DeserializeObject(Json); } /// /// 字串反序列化成指定对象实体(列表) /// /// 实体类型 /// 字串 /// public static List ToList(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject>(Json); } /// /// 字串反序列化成DataTable /// /// 字串 /// public static DataTable ToTable(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject(Json); } /// /// 字串反序列化成linq对象 /// /// 字串 /// public static JObject ToJObject(this string Json) { return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", "")); } public static DataTable GetAttributesDataTable(this object obj) { var tb = new DataTable(obj.GetType().Name); tb.Columns.Add("信号说明", typeof(string)); tb.Columns.Add("信号名称", typeof(string)); tb.Columns.Add("信号值", typeof(string)); Type t = obj.GetType(); //属性遍历 foreach (System.Reflection.PropertyInfo pi in t.GetProperties()) { AttributeCollection attributes = TypeDescriptor.GetProperties(t)[pi.Name].Attributes; DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)]; string describle = myAttribute.Description; string proname = pi.Name; var abc = pi.GetValue(obj, null); var values = new object[3]; values[0] = describle; values[1] = proname; values[2] = abc; tb.Rows.Add(values); } return tb; } } }