DataSerializer.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using ProtoBuf;
  2. using ProtoBuf.Meta;
  3. using ServiceStack.Text;
  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. return JsonSerializer.DeserializeFromStream(type, stream);
  39. }
  40. throw new NotImplementedException();
  41. }
  42. /// <summary>
  43. /// Serializes to json.
  44. /// </summary>
  45. /// <param name="obj">The obj.</param>
  46. /// <returns>System.String.</returns>
  47. public static string SerializeToJsonString(object obj)
  48. {
  49. return JsonSerializer.SerializeToString(obj, obj.GetType());
  50. }
  51. /// <summary>
  52. /// Configures this instance.
  53. /// </summary>
  54. public static void Configure()
  55. {
  56. JsConfig.DateHandler = JsonDateHandler.ISO8601;
  57. JsConfig.ExcludeTypeInfo = true;
  58. JsConfig.IncludeNullValues = false;
  59. }
  60. }
  61. }