SystemTextJsonSerializer.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.Json;
  4. namespace SocketIOClient.JsonSerializer
  5. {
  6. public class SystemTextJsonSerializer : IJsonSerializer
  7. {
  8. public JsonSerializeResult Serialize(object[] data)
  9. {
  10. var converter = new ByteArrayConverter();
  11. var options = GetOptions();
  12. options.Converters.Add(converter);
  13. string json = System.Text.Json.JsonSerializer.Serialize(data, options);
  14. return new JsonSerializeResult
  15. {
  16. Json = json,
  17. Bytes = converter.Bytes
  18. };
  19. }
  20. public T Deserialize<T>(string json)
  21. {
  22. var options = GetOptions();
  23. return System.Text.Json.JsonSerializer.Deserialize<T>(json, options);
  24. }
  25. public T Deserialize<T>(string json, IList<byte[]> bytes)
  26. {
  27. var options = GetOptions();
  28. var converter = new ByteArrayConverter();
  29. options.Converters.Add(converter);
  30. converter.Bytes.AddRange(bytes);
  31. return System.Text.Json.JsonSerializer.Deserialize<T>(json, options);
  32. }
  33. private JsonSerializerOptions GetOptions()
  34. {
  35. JsonSerializerOptions options = null;
  36. if (OptionsProvider != null)
  37. {
  38. options = OptionsProvider();
  39. }
  40. if (options == null)
  41. {
  42. options = new JsonSerializerOptions();
  43. }
  44. return options;
  45. }
  46. public Func<JsonSerializerOptions> OptionsProvider { get; set; }
  47. }
  48. }