NewtonsoftJsonSerializer.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using Newtonsoft.Json;
  3. using SocketIOClient.JsonSerializer;
  4. using System.Collections.Generic;
  5. namespace SocketIOClient.Newtonsoft.Json
  6. {
  7. public class NewtonsoftJsonSerializer : IJsonSerializer
  8. {
  9. public Func<JsonSerializerSettings> JsonSerializerOptions { get; }
  10. public JsonSerializeResult Serialize(object[] data)
  11. {
  12. var converter = new ByteArrayConverter();
  13. var settings = GetOptions();
  14. settings.Converters.Add(converter);
  15. string json = JsonConvert.SerializeObject(data, settings);
  16. return new JsonSerializeResult
  17. {
  18. Json = json,
  19. Bytes = converter.Bytes
  20. };
  21. }
  22. public T Deserialize<T>(string json)
  23. {
  24. var settings = GetOptions();
  25. return JsonConvert.DeserializeObject<T>(json, settings);
  26. }
  27. public T Deserialize<T>(string json, IList<byte[]> bytes)
  28. {
  29. var converter = new ByteArrayConverter();
  30. converter.Bytes.AddRange(bytes);
  31. var settings = GetOptions();
  32. settings.Converters.Add(converter);
  33. return JsonConvert.DeserializeObject<T>(json, settings);
  34. }
  35. private JsonSerializerSettings GetOptions()
  36. {
  37. JsonSerializerSettings options;
  38. if (OptionsProvider != null)
  39. {
  40. options = OptionsProvider();
  41. }
  42. else
  43. {
  44. options = CreateOptions();
  45. }
  46. if (options == null)
  47. {
  48. options = new JsonSerializerSettings();
  49. }
  50. return options;
  51. }
  52. [Obsolete("Use Options instead.")]
  53. public virtual JsonSerializerSettings CreateOptions()
  54. {
  55. return new JsonSerializerSettings();
  56. }
  57. public Func<JsonSerializerSettings> OptionsProvider { get; set; }
  58. }
  59. }