93 lines
3.1 KiB
C#
93 lines
3.1 KiB
C#
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
|
|
{
|
|
/// <summary>
|
|
/// 消息序列化工具类
|
|
/// 封装 Newtonsoft.Json 序列化/反序列化逻辑
|
|
/// </summary>
|
|
public static class MessageSerializer
|
|
{
|
|
/// <summary>
|
|
/// JSON 序列化设置
|
|
/// TypeNameHandling.Auto:保留类型信息以支持多态反序列化
|
|
/// NullValueHandling.Ignore:忽略 null 值减少传输量
|
|
/// Formatting.None:单行输出配合行协议
|
|
/// </summary>
|
|
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
|
|
{
|
|
TypeNameHandling = TypeNameHandling.All,
|
|
NullValueHandling = NullValueHandling.Ignore,
|
|
Formatting = Formatting.None
|
|
};
|
|
|
|
/// <summary>
|
|
/// 将对象序列化为 JSON 字符串
|
|
/// </summary>
|
|
/// <typeparam name="T">对象类型</typeparam>
|
|
/// <param name="obj">要序列化的对象</param>
|
|
/// <returns>JSON 字符串</returns>
|
|
public static string Serialize<T>(T obj)
|
|
{
|
|
return JsonConvert.SerializeObject(obj, Settings);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将 JSON 字符串反序列化为指定类型的对象
|
|
/// </summary>
|
|
/// <typeparam name="T">目标类型</typeparam>
|
|
/// <param name="json">JSON 字符串</param>
|
|
/// <returns>反序列化后的对象,失败时返回 null</returns>
|
|
public static T Deserialize<T>(string json) where T : class
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.DeserializeObject<T>(json, Settings);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将 JSON 字符串反序列化为命令对象
|
|
/// 根据类型信息还原为正确的命令子类实例
|
|
/// </summary>
|
|
/// <param name="json">JSON 字符串</param>
|
|
/// <returns>命令对象,失败时返回 null</returns>
|
|
public static RaySourceCommand DeserializeCommand(string json)
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.DeserializeObject<RaySourceCommand>(json, Settings);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将 JSON 字符串反序列化为响应对象
|
|
/// 根据类型信息还原为正确的响应子类实例
|
|
/// </summary>
|
|
/// <param name="json">JSON 字符串</param>
|
|
/// <returns>响应对象,失败时返回 null</returns>
|
|
public static RaySourceResponse DeserializeResponse(string json)
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.DeserializeObject<RaySourceResponse>(json, Settings);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
}
|