DataSerializer.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.IO;
  4. namespace MediaBrowser.ApiInteraction
  5. {
  6. public static class DataSerializer
  7. {
  8. /// <summary>
  9. /// This is an auto-generated Protobuf Serialization assembly for best performance.
  10. /// It is created during the Model project's post-build event.
  11. /// This means that this class can currently only handle types within the Model project.
  12. /// If we need to, we can always add a param indicating whether or not the model serializer should be used.
  13. /// </summary>
  14. private static readonly ProtobufModelSerializer ProtobufModelSerializer = new ProtobufModelSerializer();
  15. public static T DeserializeFromStream<T>(Stream stream, SerializationFormats format)
  16. where T : class
  17. {
  18. if (format == ApiInteraction.SerializationFormats.Protobuf)
  19. {
  20. return ProtobufModelSerializer.Deserialize(stream, null, typeof(T)) as T;
  21. }
  22. else if (format == ApiInteraction.SerializationFormats.Jsv)
  23. {
  24. throw new NotImplementedException();
  25. }
  26. else if (format == ApiInteraction.SerializationFormats.Json)
  27. {
  28. using (StreamReader streamReader = new StreamReader(stream))
  29. {
  30. using (JsonReader jsonReader = new JsonTextReader(streamReader))
  31. {
  32. return JsonSerializer.Create(new JsonSerializerSettings()).Deserialize<T>(jsonReader);
  33. }
  34. }
  35. }
  36. throw new NotImplementedException();
  37. }
  38. public static object DeserializeFromStream(Stream stream, SerializationFormats format, Type type)
  39. {
  40. if (format == ApiInteraction.SerializationFormats.Protobuf)
  41. {
  42. return ProtobufModelSerializer.Deserialize(stream, null, type);
  43. }
  44. else if (format == ApiInteraction.SerializationFormats.Jsv)
  45. {
  46. throw new NotImplementedException();
  47. }
  48. else if (format == ApiInteraction.SerializationFormats.Json)
  49. {
  50. using (StreamReader streamReader = new StreamReader(stream))
  51. {
  52. using (JsonReader jsonReader = new JsonTextReader(streamReader))
  53. {
  54. return JsonSerializer.Create(new JsonSerializerSettings()).Deserialize(jsonReader, type);
  55. }
  56. }
  57. }
  58. throw new NotImplementedException();
  59. }
  60. public static void Configure()
  61. {
  62. }
  63. public static bool CanDeSerializeJsv
  64. {
  65. get
  66. {
  67. return false;
  68. }
  69. }
  70. }
  71. }