using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; //using System.Runtime.Serialization.Formatters.Binary; namespace nettyCommunication { public class JsonByByteToObjectTools { public static byte[] ObjToJsonByte(AbstractMessage message) { try { string objstr = JsonConvert.SerializeObject(message); byte[] buffer = Encoding.UTF8.GetBytes(objstr); return buffer; } catch { Console.WriteLine("tobytes异常"); return null; } } public static AbstractMessage JsonByteToObj(byte[] bstr) where AbstractMessage : class { try { int count = 0; for (int i = 0; i < bstr.Length; i++) { if (bstr[i] == 0) { count = i; break; } } string str = new UTF8Encoding().GetString(bstr,0,count); AbstractMessage msg = JsonConvert.DeserializeObject(str); return msg; } catch { Console.WriteLine("Json byte to msg异常"); return null; } } } }