Object转Json 源码

  1 using System;
  2 using System.Collections;
  3 using System.Reflection;
  4 using System.Text;
  5 
  6 namespace JSON
  7 {
  8     /// <summary>
  9     /// 模型转为JSON
 10     /// </summary>
 11     public static class ModelToJsonEx
 12     {
 13         #region 基础转换
 14         /// <summary>
 15         /// 对象转换为Json
 16         /// </summary>
 17         /// <param name="obj">对象实例</param>
 18         /// <returns>Json字符串</returns>
 19         public static string MToJson(this Object obj)
 20         {
 21             switch (obj)
 22             {
 23                 case Guid guid:
 24                     return $"\"{guid.ToString()}\"";
 25                 case IList list:
 26                     return MIListToJson(list, null);
 27                 default:
 28                     return MObjectToJson(obj, null);
 29             }
 30         }
 31         /// <summary>
 32         /// 对象转换为Json
 33         /// </summary>
 34         /// <param name="obj">对象实例</param>
 35         /// <param name="ignores">忽略输出的属性(不区分大小写)</param>
 36         /// <returns>Json字符串</returns>
 37         public static string MToJson(this Object obj, params string[] ignores)
 38         {
 39             switch (obj)
 40             {
 41                 //TODO:特殊类型转换添加到此处
 42                 case Guid value:
 43                     return $"\"{value.ToString()}\"";
 44                 case IList value:
 45                     return MIListToJson(value, ignores);
 46                 case IDictionary value:
 47                     return MIDictionaryToJson(value, ignores);
 48                 case Object value:
 49                     return MObjectToJson(obj, ignores);
 50                 default:
 51                     throw new NotImplementedException("无法识别对象!");
 52             }
 53         }
 54         /// <summary>
 55         /// 组类型转换为Json
 56         /// </summary>
 57         /// <param name="list">组类型</param>
 58         /// <param name="ignores">忽略输出的属性</param>
 59         /// <returns>Json字符串</returns>
 60         public static string MIListToJson(this IList list, params string[] ignores)
 61         {
 62             StringBuilder builder = new StringBuilder("[");
 63             //转换值为json字符串
 64             foreach (var value in list) builder.Append(MValueToJson(value, ignores) + ',');
 65             //有内容时去除多余间隔符
 66             if (list.Count > 0)
 67             {
 68                 //去除多余间隔符
 69                 builder.Remove(builder.Length - 1, 1);
 70             }
 71             //添加结尾符
 72             builder.Append("]");
 73             return builder.ToString();
 74         }
 75         /// <summary>
 76         /// 字典类型转换为Json字符串
 77         /// </summary>
 78         /// <param name="dictionary"></param>
 79         /// <param name="ignores"></param>
 80         /// <returns>Json字符串</returns>
 81         public static string MIDictionaryToJson(this IDictionary dictionary, params string[] ignores)
 82         {
 83             StringBuilder builder = new StringBuilder("[");
 84             foreach (var key in dictionary.Keys)
 85             {
 86                 var value = dictionary[key];
 87                 //外边界
 88                 builder.Append("[");
 89                 //转换key
 90                 builder.Append(MValueToJson(key, ignores));
 91                 //分隔
 92                 builder.Append(",");
 93                 //转换value
 94                 builder.Append(MValueToJson(value, ignores));
 95                 //尾边界
 96                 builder.Append("],");
 97             }
 98             //有内容时去除多余间隔符
 99             if (dictionary.Count > 0)
100             {
101                 //去除多余间隔符
102                 builder.Remove(builder.Length - 1, 1);
103             }
104             builder.Append("]");
105             return builder.ToString();
106         }
107         /// <summary>
108         /// 对象转换为Json
109         /// </summary>
110         /// <param name="obj">对象实例</param>
111         /// <param name="ignores">忽略输出的属性</param>
112         /// <returns>Json字符串</returns>
113         public static string MObjectToJson(this Object obj, params string[] ignores)
114         {
115             PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
116             StringBuilder builder = new StringBuilder("{");
117 
118             foreach (var property in properties)
119             {
120                 if (null != ignores && ignores.Length > 0 && ignores.Any(g => g.ToLower() == property.Name.ToLower()))
121                 {
122                     continue;
123                 }
124                 else
125                 {
126                     //此属性json表示字符
127                     string str_property = string.Empty;
128                     //属性名称格式
129                     str_property = $"\"{property.Name}\":";
130                     //获取此属性值
131                     Object value = property.GetValue(obj);
132                     //添加此属性值
133                     str_property += MValueToJson(value, ignores);
134                     //是否添加间隔符
135                     builder.Append(str_property + ',');
136                 }
137             }
138             //有内容时去除多余间隔符
139             if (properties.Length > 0)
140             {
141                 //去除多余间隔符
142                 builder.Remove(builder.Length - 1, 1);
143             }
144             //添加结尾
145             builder.Append("}");
146             return builder.ToString();
147         }
148         /// <summary>
149         /// 转换值为Json字符串
150         /// </summary>
151         /// <param name="value"></param>
152         /// <param name="ignores">忽略字段</param>
153         /// <returns></returns>
154         public static string MValueToJson(this object value, params string[] ignores)
155         {
156             string str_property = string.Empty;
157             //获取此属性类型标识
158             TypeCode code = Convert.GetTypeCode(value);
159             switch (code)
160             {
161                 case TypeCode.Empty:
162                     str_property += "null";
163                     break;
164                 case TypeCode.Object:
165                     str_property += MToJson(value, ignores);
166                     break;
167                 case TypeCode.Boolean:
168                     str_property += value.ToString().ToLower();
169                     break;
170                 case TypeCode.SByte:
171                 case TypeCode.Byte:
172                 case TypeCode.Int16:
173                 case TypeCode.UInt16:
174                 case TypeCode.Int32:
175                 case TypeCode.UInt32:
176                 case TypeCode.Int64:
177                 case TypeCode.UInt64:
178                 case TypeCode.Single:
179                 case TypeCode.Double:
180                 case TypeCode.Decimal:
181                     str_property += value;
182                     break;
183                 case TypeCode.Char:
184                     str_property += $"\"{(((Char)value != Char.MinValue) ? value : string.Empty)}\"";
185                     break;
186                 case TypeCode.String:
187                     str_property += $"\"{(((String)value != String.Empty) ? value : string.Empty)}\"";
188                     break;
189                 case TypeCode.DateTime:
190                     str_property += $"\"{Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss")}\"";
191                     break;
192                 case TypeCode.DBNull:
193                 default:
194                     throw new NotImplementedException("无法识别对象!");
195             }
196             return str_property;
197         }
198         /// <summary>
199         /// 查看数组是否包含此字段
200         /// </summary>
201         /// <typeparam name="T">数组类型</typeparam>
202         /// <param name="arr">数组实例</param>
203         /// <param name="any">比较方法</param>
204         /// <returns></returns>
205         public static bool Any<T>(this T[] arr, Any<T, bool> any)
206         {
207             foreach (var obj in arr) if (any(obj)) return true;
208 
209             return false;
210         }
211         #endregion
212     }
213     /// <summary>
214     /// 自定义拉姆达表达式
215     /// </summary>
216     /// <typeparam name="T"></typeparam>
217     /// <typeparam name="T1"></typeparam>
218     /// <param name="t"></param>
219     /// <returns></returns>
220     public delegate T1 Any<in T, out T1>(T t);
221 }

猜你喜欢

转载自www.cnblogs.com/Jzs001/p/13195247.html