SystemTextJsonSerializer.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System.Text.Json;
  2. using CacheManager.Core.Internal;
  3. namespace Hotline.CacheManager
  4. {
  5. public class SystemTextJsonSerializer: CacheSerializer
  6. {
  7. private static readonly Type OpenGenericType = typeof(JsonCacheItem<>);
  8. private readonly JsonSerializerOptions _jsonSerializerOptions;
  9. public SystemTextJsonSerializer(JsonSerializerOptions jsonSerializerOptions)
  10. {
  11. _jsonSerializerOptions = jsonSerializerOptions;
  12. }
  13. public SystemTextJsonSerializer(): this(new JsonSerializerOptions(JsonSerializerDefaults.Web))
  14. {
  15. }
  16. protected override Type GetOpenGeneric()
  17. {
  18. return OpenGenericType;
  19. }
  20. protected override object CreateNewItem<TCacheValue>(ICacheItemProperties properties, object value)
  21. {
  22. return new JsonCacheItem<TCacheValue>(properties, value);
  23. }
  24. public override byte[] Serialize<T>(T value)
  25. {
  26. return JsonSerializer.SerializeToUtf8Bytes(value, _jsonSerializerOptions);
  27. }
  28. public override object Deserialize(byte[] data, Type target)
  29. {
  30. return JsonSerializer.Deserialize(data, target, _jsonSerializerOptions);
  31. }
  32. }
  33. }