using System.Text; using System.Text.Json; namespace DramaLing.Api.Services.Infrastructure.Caching; public class JsonCacheSerializer : ICacheSerializer { private readonly JsonSerializerOptions _options; private readonly ILogger _logger; public JsonCacheSerializer(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = false }; } public byte[] Serialize(T value) where T : class { try { var json = JsonSerializer.Serialize(value, _options); return Encoding.UTF8.GetBytes(json); } catch (Exception ex) { _logger.LogError(ex, "Error serializing cache value of type {Type}", typeof(T).Name); throw; } } public T? Deserialize(byte[] data) where T : class { try { var json = Encoding.UTF8.GetString(data); return JsonSerializer.Deserialize(json, _options); } catch (Exception ex) { _logger.LogError(ex, "Error deserializing cache data to type {Type}", typeof(T).Name); return null; } } }