JsonHelper.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.Serialization.Json;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace ToolsClassLibrary
  10. {
  11. /// <summary>
  12. /// Json工具类
  13. /// </summary>
  14. public static class JsonHelper
  15. {
  16. /// <summary>
  17. /// Json序列化
  18. /// </summary>
  19. public static string JsonSerializer<T>(T obj)
  20. {
  21. string jsonString = string.Empty;
  22. try
  23. {
  24. DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  25. using (MemoryStream ms = new MemoryStream())
  26. {
  27. serializer.WriteObject(ms, obj);
  28. jsonString = Encoding.UTF8.GetString(ms.ToArray());
  29. }
  30. }
  31. catch
  32. {
  33. jsonString = string.Empty;
  34. }
  35. return jsonString;
  36. }
  37. /// <summary>
  38. /// Json反序列化
  39. /// </summary>
  40. public static T JsonDeserialize<T>(string jsonString)
  41. {
  42. T obj = Activator.CreateInstance<T>();
  43. try
  44. {
  45. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
  46. {
  47. DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());//typeof(T)
  48. T jsonObject = (T)ser.ReadObject(ms);
  49. ms.Close();
  50. return jsonObject;
  51. }
  52. }
  53. catch
  54. {
  55. return default(T);
  56. }
  57. }
  58. public static byte[] SerializeBinary(object request)
  59. {
  60. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
  61. new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  62. System.IO.MemoryStream memStream = new System.IO.MemoryStream();
  63. serializer.Serialize(memStream, request);
  64. byte[] result=memStream.GetBuffer();
  65. memStream.Close();
  66. return result;
  67. }
  68. public static object DeSerializeBinary(byte[] buffer)
  69. {
  70. System.IO.MemoryStream memStream = new MemoryStream(buffer);
  71. memStream.Position = 0;
  72. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =
  73. new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  74. object newobj = new double[2];
  75. try
  76. {
  77. newobj = deserializer.Deserialize(memStream);
  78. }
  79. catch (Exception e)
  80. {
  81. Console.WriteLine(e.Message.ToString());
  82. }
  83. memStream.Close();
  84. return newobj;
  85. }
  86. }
  87. }