JSONUtil.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. namespace CB.Common
  6. {
  7. /// <summary>
  8. /// json操作类
  9. /// </summary>
  10. public class JSONUtil
  11. {
  12. /// <summary>
  13. /// 列表到json
  14. /// </summary>
  15. /// <typeparam name="T"></typeparam>
  16. /// <param name="jsonName"></param>
  17. /// <param name="IL"></param>
  18. /// <returns></returns>
  19. public static string ObjectToJson<T>(IList<T> IL)
  20. {
  21. StringBuilder Json = new StringBuilder();
  22. Json.Append("[");
  23. if (IL.Count > 0)
  24. {
  25. for (int i = 0; i < IL.Count; i++)
  26. {
  27. T obj = Activator.CreateInstance<T>();
  28. Type type = obj.GetType();
  29. PropertyInfo[] pis = type.GetProperties();
  30. Json.Append("{");
  31. for (int j = 0; j < pis.Length; j++)
  32. {
  33. Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
  34. if (j < pis.Length - 1)
  35. {
  36. Json.Append(",");
  37. }
  38. }
  39. Json.Append("}");
  40. if (i < IL.Count - 1)
  41. {
  42. Json.Append(",");
  43. }
  44. }
  45. }
  46. Json.Append("]");
  47. return Json.ToString();
  48. }
  49. public static string GetJSON<T>(T t)
  50. {
  51. string result = String.Empty;
  52. try
  53. {
  54. System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
  55. new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
  56. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  57. {
  58. serializer.WriteObject(ms, t);
  59. result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. throw ex;
  65. }
  66. return result;
  67. }
  68. /// <summary>
  69. /// 把json还原为对象
  70. /// </summary>
  71. /// <typeparam name="T">对象类型</typeparam>
  72. /// <param name="jsonStr">json字符串</param>
  73. /// <returns>T 对象类型</returns>
  74. public static T ParseFormByJson<T>(string jsonStr)
  75. {
  76. T obj = Activator.CreateInstance<T>();
  77. using (System.IO.MemoryStream ms =
  78. new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
  79. {
  80. System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
  81. new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
  82. return (T)serializer.ReadObject(ms);
  83. }
  84. }
  85. }
  86. }