JsonByByteToObjectTools.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Newtonsoft.Json;
  7. //using System.Runtime.Serialization.Formatters.Binary;
  8. namespace nettyCommunication
  9. {
  10. public class JsonByByteToObjectTools
  11. {
  12. public static byte[] ObjToJsonByte(AbstractMessage message)
  13. {
  14. try
  15. {
  16. string objstr = JsonConvert.SerializeObject(message);
  17. byte[] buffer = Encoding.UTF8.GetBytes(objstr);
  18. return buffer;
  19. }
  20. catch { Console.WriteLine("tobytes异常"); return null; }
  21. }
  22. public static AbstractMessage JsonByteToObj<AbstractMessage>(byte[] bstr) where AbstractMessage : class
  23. {
  24. try
  25. {
  26. int count = 0;
  27. for (int i = 0; i < bstr.Length; i++)
  28. {
  29. if (bstr[i] == 0)
  30. {
  31. count = i;
  32. break;
  33. }
  34. }
  35. string str = new UTF8Encoding().GetString(bstr,0,count);
  36. AbstractMessage msg = JsonConvert.DeserializeObject<AbstractMessage>(str);
  37. return msg;
  38. }
  39. catch { Console.WriteLine("Json byte to msg异常"); return null; }
  40. }
  41. }
  42. }