123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- 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<AbstractMessage>(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<AbstractMessage>(str);
- return msg;
- }
- catch { Console.WriteLine("Json byte to msg异常"); return null; }
- }
- }
- }
|