DataSerializer.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Newtonsoft.Json;
  2. using ProtoBuf;
  3. using ProtoBuf.Meta;
  4. using System;
  5. using System.IO;
  6. namespace MediaBrowser.ApiInteraction
  7. {
  8. /// <summary>
  9. /// Class DataSerializer
  10. /// </summary>
  11. public static class DataSerializer
  12. {
  13. /// <summary>
  14. /// Gets or sets the dynamically created serializer.
  15. /// </summary>
  16. /// <value>The dynamic serializer.</value>
  17. public static TypeModel DynamicSerializer { get; set; }
  18. /// <summary>
  19. /// Deserializes an object
  20. /// </summary>
  21. /// <param name="stream">The stream.</param>
  22. /// <param name="format">The format.</param>
  23. /// <param name="type">The type.</param>
  24. /// <returns>System.Object.</returns>
  25. /// <exception cref="System.NotImplementedException"></exception>
  26. public static object DeserializeFromStream(Stream stream, SerializationFormats format, Type type)
  27. {
  28. if (format == SerializationFormats.Protobuf)
  29. {
  30. if (DynamicSerializer != null)
  31. {
  32. return DynamicSerializer.Deserialize(stream, null, type);
  33. }
  34. return Serializer.NonGeneric.Deserialize(type, stream);
  35. }
  36. if (format == SerializationFormats.Json)
  37. {
  38. using (var streamReader = new StreamReader(stream))
  39. {
  40. using (var jsonReader = new JsonTextReader(streamReader))
  41. {
  42. return JsonSerializer.Create(new JsonSerializerSettings()).Deserialize(jsonReader, type);
  43. }
  44. }
  45. }
  46. throw new NotImplementedException();
  47. }
  48. /// <summary>
  49. /// Serializes to json.
  50. /// </summary>
  51. /// <param name="obj">The obj.</param>
  52. /// <returns>System.String.</returns>
  53. public static string SerializeToJsonString(object obj)
  54. {
  55. using (var streamWriter = new StringWriter())
  56. {
  57. using (var jsonWriter = new JsonTextWriter((streamWriter)))
  58. {
  59. JsonSerializer.Create(new JsonSerializerSettings()).Serialize(jsonWriter, obj);
  60. }
  61. return streamWriter.ToString();
  62. }
  63. }
  64. /// <summary>
  65. /// Configures this instance.
  66. /// </summary>
  67. public static void Configure()
  68. {
  69. }
  70. }
  71. }