using System.Text; using System.Text.Json; using CoreAgent.WebSocketTransport.Interfaces; namespace CoreAgent.WebSocketTransport.Services; /// /// JSON 消息序列化器 /// 单一职责:负责消息的序列化和反序列化 /// public class JsonMessageSerializer : IMessageSerializer { private readonly JsonSerializerOptions _options; public JsonMessageSerializer(JsonSerializerOptions? options = null) { _options = options ?? new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false }; } public byte[] Serialize(T message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var json = JsonSerializer.Serialize(message, _options); return Encoding.UTF8.GetBytes(json); } public T? Deserialize(byte[] data) { if (data == null || data.Length == 0) { return default; } var json = Encoding.UTF8.GetString(data); return JsonSerializer.Deserialize(json, _options); } public T? Deserialize(string json) { if (string.IsNullOrEmpty(json)) { return default; } return JsonSerializer.Deserialize(json, _options); } }