终端一体化运控平台
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

93 wiersze
3.0 KiB

  1. using BPA.Helper;
  2. using Newtonsoft.Json.Linq;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace BPASmartClient.JXJFoodBigStation.Model.MQTT.Message
  10. {
  11. public static class MsgPackExtensionMethod
  12. {
  13. public static MsgPackage Deserialize(this string msg)
  14. {
  15. if (msg != null)
  16. {
  17. if (msg.Iskey("MessageId") && msg.Iskey("Message") && msg.Iskey("MessageLen"))
  18. {
  19. var obj = msg.FromJSON<MsgPackage>();
  20. if (obj != null)
  21. return obj;
  22. }
  23. else
  24. {
  25. var id = msg.ToLower().GetJsonObjValue("messageid");
  26. if (int.TryParse(id, out int tempId))
  27. {
  28. if (MessageDefine.MSG.ContainsKey(tempId))
  29. {
  30. MsgPackage package = new MsgPackage();
  31. package.MessageId = tempId;
  32. if (int.TryParse(msg.ToLower().GetJsonObjValue("messagelen"), out int tempLen))
  33. package.MessageLen = tempLen;
  34. var res = msg.ToLower().GetJsonObjValue("message");
  35. if (res != null)
  36. {
  37. package.Message = (IMessage)JsonConvert.DeserializeObject(res, MessageDefine.MSG[tempId]);
  38. }
  39. return package;
  40. }
  41. }
  42. }
  43. }
  44. return new MsgPackage();
  45. }
  46. public static string Serialize(this IMessage mes)
  47. {
  48. MsgPackage msg = new MsgPackage();
  49. var res = MessageDefine.MSG.FirstOrDefault(p => p.Value == mes.GetType());
  50. msg.MessageId = res.Key;
  51. msg.MessageLen = JsonConvert.SerializeObject(mes).Length;
  52. msg.Message = mes;
  53. return JsonConvert.SerializeObject(msg);
  54. }
  55. public static string GetJsonObjValue(this string input, string key)
  56. {
  57. try
  58. {
  59. JObject jo = (JObject)JsonConvert.DeserializeObject(input);
  60. if (jo != null && jo.ContainsKey(key))
  61. return jo[key].ToString();
  62. else
  63. return string.Empty;
  64. }
  65. catch (Exception EX)
  66. {
  67. MessageLog.GetInstance.ShowEx(EX.ToString());
  68. return string.Empty;
  69. }
  70. }
  71. public static bool Iskey(this string input, string key)
  72. {
  73. try
  74. {
  75. JObject jo = (JObject)JsonConvert.DeserializeObject(input);
  76. return jo != null && jo.ContainsKey(key);
  77. }
  78. catch (Exception EX)
  79. {
  80. MessageLog.GetInstance.ShowEx(EX.ToString());
  81. return false;
  82. }
  83. }
  84. }
  85. }