A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-8-11 17:24  /  698 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

转自:http://www.jb51.net/article/43699.htm
这篇文章主要介绍了C#实现简单的JSON序列化功能,大家可以参考使用
好久没有做web了,JSON目前比较流行,闲得没事,所以动手试试将对象序列化为JSON字符(尽管DotNet Framework已经有现成的库,也有比较好的第三方开源库),而且只是实现了处理简单的类型,并且DateTime处理的也不专业,有兴趣的筒子可以扩展,代码比较简单,反序列化木有实现:( ,直接贴代码吧,都有注释了,所以废话不多说 :)

  1. <P>
  2. 测试类/// <summary>
  3.     /// Nested class of Person.
  4.     /// </summary>
  5.     public class House
  6.     {
  7.         public string Name
  8.         {
  9.             get;
  10.             set;
  11.         }
  12.         public double Price
  13.         {
  14.             get;
  15.             set;
  16.         }
  17.     }
  18.     /// <summary>
  19.     /// Person dummy class
  20.     /// </summary>
  21.     public class Person
  22.     {
  23.         public string Name
  24.         {
  25.             get;
  26.             set;
  27.         }
  28.         public int Age
  29.         {
  30.             get;
  31.             set;
  32.         }
  33.         public string Address
  34.         {
  35.             get;
  36.             set;
  37.         }
  38.         private int h = 12;
  39.         public bool IsMarried
  40.         {
  41.             get;
  42.             set;
  43.         }
  44.         public string[] Names
  45.         {
  46.             get;
  47.             set;
  48.         }
  49.         public int[] Ages
  50.         {
  51.             get;
  52.             set;
  53.         }
  54.         public House MyHouse
  55.         {
  56.             get;
  57.             set;
  58.         }
  59.         public DateTime BirthDay
  60.         {
  61.             get;
  62.             set;
  63.         }
  64.         public List<string> Friends
  65.         {
  66.             get;
  67.             set;
  68.         }
  69.         public List<int> LoveNumbers
  70.         {
  71.             get;
  72.             set;
  73.         }
  74.     }</P>
  75. <DIV class=blockcode>
  76. <BLOCKQUOTE>
  77. 接口定义 /// <summary>
  78. /// IJsonSerializer interface.
  79. /// </summary>
  80. interface IJsonSerializer
  81. {
  82. /// <summary>
  83. /// Serialize object to json string.
  84. /// </summary>
  85. /// <typeparam name="T">The type to be serialized.</typeparam>
  86. /// <param name="obj">Instance of the type T.</param>
  87. /// <returns>json string.</returns>
  88. string Serialize(object obj);
  89. /// <summary>
  90. /// Deserialize json string to object.
  91. /// </summary>
  92. /// <typeparam name="T">The type to be deserialized.</typeparam>
  93. /// <param name="jsonString">json string.</param>
  94. /// <returns>instance of type T.</returns>
  95. T Deserialize<T>(string jsonString);
  96. }
复制代码

接口实现,还有待完善..

  1. /// <summary>
  2. /// Implement IJsonSerializer, but Deserialize had not been implemented.
  3. /// </summary>
  4. public class JsonSerializer : IJsonSerializer
  5. {
  6. /// <summary>
  7. /// Serialize object to json string.
  8. /// </summary>
  9. /// <typeparam name="T">The type to be serialized.</typeparam>
  10. /// <param name="obj">Instance of the type T.</param>
  11. /// <returns>json string.</returns>
  12. public string Serialize(object obj)
  13. {
  14. if (obj == null)
  15. {
  16. return "{}";
  17. }
  18. // Get the type of obj.
  19. Type t = obj.GetType();
  20. // Just deal with the public instance properties. others ignored.
  21. BindingFlags bf = BindingFlags.Instance | BindingFlags.Public;
  22. PropertyInfo[] pis = t.GetProperties(bf);
  23. StringBuilder json = new StringBuilder("{");
  24. if (pis != null && pis.Length > 0)
  25. {
  26. int i = 0;
  27. int lastIndex = pis.Length - 1;
  28. foreach (PropertyInfo p in pis)
  29. {
  30. // Simple string
  31. if (p.PropertyType.Equals(typeof(string)))
  32. {
  33. json.AppendFormat("\"{0}\":\"{1}\"", p.Name, p.GetValue(obj, null));
  34. }
  35. // Number,boolean.
  36. else if (p.PropertyType.Equals(typeof(int)) ||
  37. p.PropertyType.Equals(typeof(bool)) ||
  38. p.PropertyType.Equals(typeof(double)) ||
  39. p.PropertyType.Equals(typeof(decimal))
  40. )
  41. {
  42. json.AppendFormat("\"{0}\":{1}", p.Name, p.GetValue(obj, null).ToString().ToLower());
  43. }
  44. // Array.
  45. else if (isArrayType(p.PropertyType))
  46. {
  47. // Array case.
  48. object o = p.GetValue(obj, null);
  49. if (o == null)
  50. {
  51. json.AppendFormat("\"{0}\":{1}", p.Name, "null");
  52. }
  53. else
  54. {
  55. json.AppendFormat("\"{0}\":{1}", p.Name, getArrayValue((Array)p.GetValue(obj, null)));
  56. }
  57. }
  58. // Class type. custom class, list collections and so forth.
  59. else if (isCustomClassType(p.PropertyType))
  60. {
  61. object v = p.GetValue(obj, null);
  62. if (v is IList)
  63. {
  64. IList il = v as IList;
  65. string subJsString = getIListValue(il);
  66. json.AppendFormat("\"{0}\":{1}", p.Name, subJsString);
  67. }
  68. else
  69. {
  70. // Normal class type.
  71. string subJsString = Serialize(p.GetValue(obj, null));
  72. json.AppendFormat("\"{0}\":{1}", p.Name, subJsString);
  73. }
  74. }
  75. // Datetime
  76. else if (p.PropertyType.Equals(typeof(DateTime)))
  77. {
  78. DateTime dt = (DateTime)p.GetValue(obj, null);
  79. if (dt == default(DateTime))
  80. {
  81. json.AppendFormat("\"{0}\":\"\"", p.Name);
  82. }
  83. else
  84. {
  85. json.AppendFormat("\"{0}\":\"{1}\"", p.Name, ((DateTime)p.GetValue(obj, null)).ToString("yyyy-MM-dd HH:mm:ss"));
  86. }
  87. }
  88. else
  89. {
  90. // TODO: extend.
  91. }
  92. if (i >= 0 && i != lastIndex)
  93. {
  94. json.Append(",");
  95. }
  96. ++i;
  97. }
  98. }
  99. json.Append("}");
  100. return json.ToString();
  101. }
  102. /// <summary>
  103. /// Deserialize json string to object.
  104. /// </summary>
  105. /// <typeparam name="T">The type to be deserialized.</typeparam>
  106. /// <param name="jsonString">json string.</param>
  107. /// <returns>instance of type T.</returns>
  108. public T Deserialize<T>(string jsonString)
  109. {
  110. throw new NotImplementedException("Not implemented :(");
  111. }
  112. /// <summary>
  113. /// Get array json format string value.
  114. /// </summary>
  115. /// <param name="obj">array object</param>
  116. /// <returns>js format array string.</returns>
  117. string getArrayValue(Array obj)
  118. {
  119. if (obj != null)
  120. {
  121. if (obj.Length == 0)
  122. {
  123. return "[]";
  124. }
  125. object firstElement = obj.GetValue(0);
  126. Type et = firstElement.GetType();
  127. bool quotable = et == typeof(string);
  128. StringBuilder sb = new StringBuilder("[");
  129. int index = 0;
  130. int lastIndex = obj.Length - 1;
  131. if (quotable)
  132. {
  133. foreach (var item in obj)
  134. {
  135. sb.AppendFormat("\"{0}\"", item.ToString());
  136. if (index >= 0 && index != lastIndex)
  137. {
  138. sb.Append(",");
  139. }
  140. ++index;
  141. }
  142. }
  143. else
  144. {
  145. foreach (var item in obj)
  146. {
  147. sb.Append(item.ToString());
  148. if (index >= 0 && index != lastIndex)
  149. {
  150. sb.Append(",");
  151. }
  152. ++index;
  153. }
  154. }
  155. sb.Append("]");
  156. return sb.ToString();
  157. }
  158. return "null";
  159. }
  160. /// <summary>
  161. /// Get Ilist json format string value.
  162. /// </summary>
  163. /// <param name="obj">IList object</param>
  164. /// <returns>js format IList string.</returns>
  165. string getIListValue(IList obj)
  166. {
  167. if (obj != null)
  168. {
  169. if (obj.Count == 0)
  170. {
  171. return "[]";
  172. }
  173. object firstElement = obj[0];
  174. Type et = firstElement.GetType();
  175. bool quotable = et == typeof(string);
  176. StringBuilder sb = new StringBuilder("[");
  177. int index = 0;
  178. int lastIndex = obj.Count - 1;
  179. if (quotable)
  180. {
  181. foreach (var item in obj)
  182. {
  183. sb.AppendFormat("\"{0}\"", item.ToString());
  184. if (index >= 0 && index != lastIndex)
  185. {
  186. sb.Append(",");
  187. }
  188. ++index;
  189. }
  190. }
  191. else
  192. {
  193. foreach (var item in obj)
  194. {
  195. sb.Append(item.ToString());
  196. if (index >= 0 && index != lastIndex)
  197. {
  198. sb.Append(",");
  199. }
  200. ++index;
  201. }
  202. }
  203. sb.Append("]");
  204. return sb.ToString();
  205. }
  206. return "null";
  207. }
  208. /// <summary>
  209. /// Check whether t is array type.
  210. /// </summary>
  211. /// <param name="t"></param>
  212. /// <returns></returns>
  213. bool isArrayType(Type t)
  214. {
  215. if (t != null)
  216. {
  217. return t.IsArray;
  218. }
  219. return false;
  220. }
  221. /// <summary>
  222. /// Check whether t is custom class type.
  223. /// </summary>
  224. /// <param name="t"></param>
  225. /// <returns></returns>
  226. bool isCustomClassType(Type t)
  227. {
  228. if (t != null)
  229. {
  230. return t.IsClass && t != typeof(string);
  231. }
  232. return false;
  233. }
  234. }
复制代码

测试代码

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Person ps = new Person()
  6. {
  7. Name = "Leon",
  8. Age = 25,
  9. Address = "China",
  10. IsMarried = false,
  11. Names = new string[] { "wgc", "leon", "giantfish" },
  12. Ages = new int[] { 1, 2, 3, 4 },
  13. MyHouse = new House()
  14. {
  15. Name = "HouseName",
  16. Price = 100.01,
  17. },
  18. BirthDay = new DateTime(1986, 12, 20, 12, 12, 10),
  19. Friends = new List<string>() { "friend1", "friend2" },
  20. LoveNumbers = new List<int>() { 1, 2, 3 }
  21. };
  22. IJsonSerializer js = new JsonSerializer();
  23. string s = js.Serialize(ps);
  24. Console.WriteLine(s);
  25. Console.ReadKey();
  26. }
  27. }
复制代码

生成的 JSON字符串 :

  1. {"Name":"Leon","Age":25,"Address":"China","IsMarried":false,"Names":["wgc","leon","giantfish"],"Ages":[1,2,3,4],"MyHouse":{"Name":"HouseName","Price":100.01},"BirthDay":"1986-12-20 12:12:10","Friends":["friend1","friend2"],"LoveNumbers":[1,2,3]}
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马