using IpcLibrary.Core; using IpcLibrary.Core.Exceptions; using IpcLibrary.Serialization; using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json; using System.Text.Json.Serialization; namespace IPCLibrary.Serialization { /// /// JSON序列化器实现 /// public class JsonMessageSerializer : IMessageSerializer { private readonly JsonSerializerOptions _options; public JsonMessageSerializer() { _options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, Converters = { new JsonStringEnumConverter(), new TypeConverter(), new ExceptionConverter() } }; } public byte[] Serialize(object obj) { try { var json = JsonSerializer.Serialize(obj, obj.GetType(), _options); return System.Text.Encoding.UTF8.GetBytes(json); } catch (Exception ex) { throw new IPCException($"序列化失败: {ex.Message}", ex); } } public T Deserialize(byte[] data) { try { var json = System.Text.Encoding.UTF8.GetString(data); return JsonSerializer.Deserialize(json, _options); } catch (Exception ex) { throw new IPCException($"反序列化失败: {ex.Message}", ex); } } public object Deserialize(byte[] data, Type type) { try { var json = System.Text.Encoding.UTF8.GetString(data); return JsonSerializer.Deserialize(json, type, _options); } catch (Exception ex) { throw new IPCException($"反序列化失败: {ex.Message}", ex); } } } }