using System; using Newtonsoft.Json; using XP.Hardware.RaySource.Comet.Messages.Commands; using XP.Hardware.RaySource.Comet.Messages.Responses; namespace XP.Hardware.RaySource.Comet.Messages { /// /// 消息序列化工具类 /// 封装 Newtonsoft.Json 序列化/反序列化逻辑 /// public static class MessageSerializer { /// /// JSON 序列化设置 /// TypeNameHandling.Auto:保留类型信息以支持多态反序列化 /// NullValueHandling.Ignore:忽略 null 值减少传输量 /// Formatting.None:单行输出配合行协议 /// private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }; /// /// 将对象序列化为 JSON 字符串 /// /// 对象类型 /// 要序列化的对象 /// JSON 字符串 public static string Serialize(T obj) { return JsonConvert.SerializeObject(obj, Settings); } /// /// 将 JSON 字符串反序列化为指定类型的对象 /// /// 目标类型 /// JSON 字符串 /// 反序列化后的对象,失败时返回 null public static T Deserialize(string json) where T : class { try { return JsonConvert.DeserializeObject(json, Settings); } catch (JsonException) { return null; } } /// /// 将 JSON 字符串反序列化为命令对象 /// 根据类型信息还原为正确的命令子类实例 /// /// JSON 字符串 /// 命令对象,失败时返回 null public static RaySourceCommand DeserializeCommand(string json) { try { return JsonConvert.DeserializeObject(json, Settings); } catch (JsonException) { return null; } } /// /// 将 JSON 字符串反序列化为响应对象 /// 根据类型信息还原为正确的响应子类实例 /// /// JSON 字符串 /// 响应对象,失败时返回 null public static RaySourceResponse DeserializeResponse(string json) { try { return JsonConvert.DeserializeObject(json, Settings); } catch (JsonException) { return null; } } } }