48 lines
1.4 KiB
C#
48 lines
1.4 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace DramaLing.Api.Services.Infrastructure.Caching;
|
|
|
|
public class JsonCacheSerializer : ICacheSerializer
|
|
{
|
|
private readonly JsonSerializerOptions _options;
|
|
private readonly ILogger<JsonCacheSerializer> _logger;
|
|
|
|
public JsonCacheSerializer(ILogger<JsonCacheSerializer> logger)
|
|
{
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
_options = new JsonSerializerOptions
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
WriteIndented = false
|
|
};
|
|
}
|
|
|
|
public byte[] Serialize<T>(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<T>(byte[] data) where T : class
|
|
{
|
|
try
|
|
{
|
|
var json = Encoding.UTF8.GetString(data);
|
|
return JsonSerializer.Deserialize<T>(json, _options);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error deserializing cache data to type {Type}", typeof(T).Name);
|
|
return null;
|
|
}
|
|
}
|
|
} |