PageRenderTime 53ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/wojilu/Serialization/JsonString.cs

https://bitbucket.org/kingshine/wojilu
C# | 323 lines | 288 code | 15 blank | 20 comment | 17 complexity | f750607e75f75e25904c3ffea85299e7 MD5 | raw file
Possible License(s): MIT
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. using System.Reflection;
  6. using wojilu.Reflection;
  7. using wojilu.ORM;
  8. namespace wojilu.Serialization {
  9. /// <summary>
  10. /// json 序列化工具:将对象转换成 json 字符串
  11. /// </summary>
  12. public class JsonString {
  13. private static Boolean getDefaultIsBreakline() {
  14. return false;
  15. }
  16. private static String empty() {
  17. return "\"\"";
  18. }
  19. /// <summary>
  20. /// 将对象转换成 json 字符串
  21. /// </summary>
  22. /// <param name="obj"></param>
  23. /// <returns></returns>
  24. public static String Convert( Object obj ) {
  25. return Convert( obj, getDefaultIsBreakline() );
  26. }
  27. /// <summary>
  28. /// 将对象转换成 json 字符串
  29. /// </summary>
  30. /// <param name="obj"></param>
  31. /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
  32. /// <returns></returns>
  33. public static String Convert( Object obj, Boolean isBreakline ) {
  34. if (obj == null) return empty();
  35. Type t = obj.GetType();
  36. if (t.IsArray) return ConvertArray( (object[])obj );
  37. if (rft.IsInterface( t, typeof( IList ) )) return ConvertList( (IList)obj );
  38. if (rft.IsInterface( t, typeof( IDictionary ) )) return ConvertDictionary( (IDictionary)obj, isBreakline );
  39. if (t == typeof( int ) ||
  40. t == typeof( decimal ) ||
  41. t == typeof( double )) {
  42. return obj.ToString();
  43. }
  44. if (t == typeof( Boolean )) return obj.ToString().ToLower();
  45. if (t == typeof( DateTime )) return "\"" + obj.ToString() + "\"";
  46. if (t == typeof( String )) {
  47. // 转义双引号,消除换行
  48. return "\"" + ClearNewLine( obj.ToString() ) + "\"";
  49. }
  50. return ConvertObject( obj, isBreakline );
  51. }
  52. /// <summary>
  53. /// 清楚json字符串中的换行符
  54. /// </summary>
  55. /// <param name="str"></param>
  56. /// <returns></returns>
  57. public static String ClearNewLine( String str ) {
  58. if (str == null) return null;
  59. return str
  60. .Replace( @"\", @"\\" )
  61. .Replace( "\"", "\\" + "\"" )
  62. .Replace( "\r", "" )
  63. .Replace( "\n", "" )
  64. .Replace( "\t", "" );
  65. }
  66. /// <summary>
  67. /// 将对象数组转换成 json 字符串
  68. /// </summary>
  69. /// <param name="arrObj"></param>
  70. /// <returns></returns>
  71. public static String ConvertArray( object[] arrObj ) {
  72. if (arrObj == null) return "[]";
  73. StringBuilder sb = new StringBuilder();
  74. sb.Append( "[ " );
  75. for (int i = 0; i < arrObj.Length; i++) {
  76. if (arrObj[i] == null) continue;
  77. sb.Append( Convert( arrObj[i], getDefaultIsBreakline() ) );
  78. if (i < arrObj.Length - 1) sb.Append( ", " );
  79. }
  80. sb.Append( " ]" );
  81. return sb.ToString();
  82. }
  83. /// <summary>
  84. /// 将对象列表转换成 json 字符串
  85. /// </summary>
  86. /// <param name="list"></param>
  87. /// <returns></returns>
  88. public static String ConvertList( IList list ) {
  89. return ConvertList( list, getDefaultIsBreakline() );
  90. }
  91. /// <summary>
  92. /// 将对象列表转换成 json 字符串
  93. /// </summary>
  94. /// <param name="list"></param>
  95. /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
  96. /// <returns></returns>
  97. public static String ConvertList( IList list, Boolean isBreakline ) {
  98. if (list == null) return "[]";
  99. StringBuilder sb = new StringBuilder();
  100. sb.Append( "[ " );
  101. if (isBreakline) sb.AppendLine();
  102. for (int i = 0; i < list.Count; i++) {
  103. if (list[i] == null) continue;
  104. sb.Append( Convert( list[i], isBreakline ) );
  105. if (i < list.Count - 1) sb.Append( ", " );
  106. if (isBreakline) sb.AppendLine();
  107. }
  108. sb.Append( " ]" );
  109. return sb.ToString();
  110. }
  111. /// <summary>
  112. /// 将字典 Dictionary 转换成 json 字符串
  113. /// </summary>
  114. /// <param name="dic"></param>
  115. /// <returns></returns>
  116. public static String ConvertDictionary( IDictionary dic ) {
  117. return ConvertDictionary( dic, getDefaultIsBreakline() );
  118. }
  119. /// <summary>
  120. /// 将字典 Dictionary 转换成 json 字符串
  121. /// </summary>
  122. /// <param name="dic"></param>
  123. /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
  124. /// <returns></returns>
  125. public static String ConvertDictionary( IDictionary dic, Boolean isBreakline ) {
  126. if (dic == null) return empty();
  127. StringBuilder builder = new StringBuilder();
  128. builder.Append( "{ " );
  129. if (isBreakline) builder.AppendLine();
  130. foreach (DictionaryEntry pair in dic) {
  131. builder.Append( "\"" );
  132. builder.Append( pair.Key );
  133. builder.Append( "\":" );
  134. builder.Append( Convert( pair.Value, isBreakline ) );
  135. builder.Append( ", " );
  136. if (isBreakline) builder.AppendLine();
  137. }
  138. String result = builder.ToString().Trim().TrimEnd( ',' );
  139. if (isBreakline) result += Environment.NewLine;
  140. return result + " }";
  141. }
  142. /// <summary>
  143. /// 将对象转换成 json 字符串
  144. /// </summary>
  145. /// <param name="obj"></param>
  146. /// <returns></returns>
  147. public static String ConvertObject( Object obj ) {
  148. return ConvertObject( obj, getDefaultIsBreakline() );
  149. }
  150. /// <summary>
  151. /// 将对象转换成 json 字符串
  152. /// </summary>
  153. /// <param name="obj"></param>
  154. /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
  155. /// <returns></returns>
  156. public static String ConvertObject( Object obj, Boolean isBreakline ) {
  157. return ConvertObject( obj, isBreakline, true );
  158. }
  159. /// <summary>
  160. /// 将对象转换成 json 字符串
  161. /// </summary>
  162. /// <param name="obj"></param>
  163. /// <param name="isBreakline">是否换行(默认不换行,阅读起来更加清晰)</param>
  164. /// <param name="withQuotation">属性名是否使用引号(默认不启用)</param>
  165. /// <returns></returns>
  166. public static String ConvertObject( Object obj, Boolean isBreakline, Boolean withQuotation ) {
  167. StringBuilder builder = new StringBuilder();
  168. builder.Append( "{ " );
  169. if (isBreakline) builder.AppendLine();
  170. PropertyInfo[] properties = obj.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance );
  171. Boolean isIdFind = false;
  172. Boolean isNameFind = false;
  173. Object idValue = "";
  174. Object nameValue = "";
  175. List<PropertyInfo> propertyList = new List<PropertyInfo>();
  176. foreach (PropertyInfo info in properties) {
  177. if (info.Name.Equals( "Id" )) {
  178. isIdFind = true;
  179. idValue = ReflectionUtil.GetPropertyValue( obj, "Id" );
  180. }
  181. else if (info.Name.Equals( "Name" )) {
  182. isNameFind = true;
  183. nameValue = ReflectionUtil.GetPropertyValue( obj, "Name" );
  184. }
  185. else {
  186. propertyList.Add( info );
  187. }
  188. }
  189. if (withQuotation) {
  190. if (isIdFind) builder.AppendFormat( "\"Id\":{0}, ", idValue );
  191. if (isNameFind) builder.AppendFormat( "\"Name\":\"{0}\", ", nameValue );
  192. }
  193. else {
  194. if (isIdFind) builder.AppendFormat( "Id:{0}, ", idValue );
  195. if (isNameFind) builder.AppendFormat( "Name:\"{0}\", ", nameValue );
  196. }
  197. foreach (PropertyInfo info in propertyList) {
  198. if (info.IsDefined( typeof( NotSerializeAttribute ), false )) {
  199. continue;
  200. }
  201. Object propertyValue = ReflectionUtil.GetPropertyValue( obj, info.Name );
  202. String jsonValue;
  203. if (info.PropertyType.IsArray) {
  204. jsonValue = ConvertArray( (object[])propertyValue );
  205. }
  206. else if (rft.IsInterface( info.PropertyType, typeof( IList ) )) {
  207. jsonValue = ConvertList( (IList)propertyValue, isBreakline );
  208. }
  209. else {
  210. jsonValue = Convert( propertyValue, isBreakline );
  211. }
  212. if (withQuotation) {
  213. builder.AppendFormat( "\"{0}\":{1}", info.Name, jsonValue );
  214. }
  215. else {
  216. builder.AppendFormat( "{0}:{1}", info.Name, jsonValue );
  217. }
  218. builder.Append( ", " );
  219. if (isBreakline) builder.AppendLine();
  220. }
  221. String result = builder.ToString().Trim().TrimEnd( ',' );
  222. if (isBreakline) result += Environment.NewLine;
  223. return result + " }";
  224. }
  225. public static String ConvertEntity( IEntity obj ) {
  226. StringBuilder builder = new StringBuilder();
  227. builder.Append( "{ " );
  228. EntityInfo ei = Entity.GetInfo( obj );
  229. List<EntityPropertyInfo> ps = ei.PropertyListAll;
  230. foreach (EntityPropertyInfo info in ps) {
  231. if (shouldPass( info )) continue;
  232. Object propertyValue = info.GetValue( obj );
  233. String jsonValue;
  234. if (propertyValue == null) {
  235. jsonValue = empty();
  236. }
  237. else {
  238. if (info.IsEntity) {
  239. jsonValue = ConvertEntity( propertyValue as IEntity );
  240. }
  241. else
  242. jsonValue = Convert( propertyValue, false );
  243. }
  244. builder.AppendFormat( "{0}:{1}", info.Name, jsonValue );
  245. builder.Append( ", " );
  246. }
  247. String result = builder.ToString().Trim().TrimEnd( ',' );
  248. return result + " }";
  249. }
  250. private static bool shouldPass( EntityPropertyInfo info ) {
  251. if (info.Type == typeof( int )) return false;
  252. if (info.Type == typeof( string )) return false;
  253. if (info.Type == typeof( decimal )) return false;
  254. if (info.Type == typeof( DateTime )) return false;
  255. if (info.Type == typeof( bool )) return false;
  256. if (info.Type == typeof( double )) return false;
  257. if (info.IsEntity) return false;
  258. return true;
  259. }
  260. }
  261. }