|
- using BPA.Helper;
- using Newtonsoft.Json.Linq;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace BPASmartClient.JXJFoodBigStation.Model.MQTT.Message
- {
- public static class MsgPackExtensionMethod
- {
- public static MsgPackage Deserialize(this string msg)
- {
- if (msg != null)
- {
- if (msg.Iskey("MessageId") && msg.Iskey("Message") && msg.Iskey("MessageLen"))
- {
- var obj = msg.FromJSON<MsgPackage>();
- if (obj != null)
- return obj;
- }
- else
- {
- var id = msg.ToLower().GetJsonObjValue("messageid");
- if (int.TryParse(id, out int tempId))
- {
- if (MessageDefine.MSG.ContainsKey(tempId))
- {
- MsgPackage package = new MsgPackage();
- package.MessageId = tempId;
- if (int.TryParse(msg.ToLower().GetJsonObjValue("messagelen"), out int tempLen))
- package.MessageLen = tempLen;
- var res = msg.ToLower().GetJsonObjValue("message");
- if (res != null)
- {
- package.Message = (IMessage)JsonConvert.DeserializeObject(res, MessageDefine.MSG[tempId]);
- }
- return package;
- }
- }
- }
-
- }
- return new MsgPackage();
- }
-
- public static string Serialize(this IMessage mes)
- {
- MsgPackage msg = new MsgPackage();
- var res = MessageDefine.MSG.FirstOrDefault(p => p.Value == mes.GetType());
- msg.MessageId = res.Key;
- msg.MessageLen = JsonConvert.SerializeObject(mes).Length;
- msg.Message = mes;
- return JsonConvert.SerializeObject(msg);
- }
-
- public static string GetJsonObjValue(this string input, string key)
- {
- try
- {
- JObject jo = (JObject)JsonConvert.DeserializeObject(input);
- if (jo != null && jo.ContainsKey(key))
- return jo[key].ToString();
- else
- return string.Empty;
-
- }
- catch (Exception EX)
- {
- MessageLog.GetInstance.ShowEx(EX.ToString());
- return string.Empty;
- }
- }
-
- public static bool Iskey(this string input, string key)
- {
- try
- {
- JObject jo = (JObject)JsonConvert.DeserializeObject(input);
- return jo != null && jo.ContainsKey(key);
- }
- catch (Exception EX)
- {
- MessageLog.GetInstance.ShowEx(EX.ToString());
- return false;
- }
- }
-
- }
- }
|