JsonSerializationHelper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using Newtonsoft.Json;
  3. namespace Abp.Json
  4. {
  5. /// <summary>
  6. /// Defines helper methods to work with JSON.
  7. /// </summary>
  8. public static class JsonSerializationHelper
  9. {
  10. private const char TypeSeperator = '|';
  11. /// <summary>
  12. /// Serializes an object with a type information included.
  13. /// So, it can be deserialized using <see cref="DeserializeWithType"/> method later.
  14. /// </summary>
  15. public static string SerializeWithType(object obj)
  16. {
  17. return SerializeWithType(obj, obj.GetType());
  18. }
  19. /// <summary>
  20. /// Serializes an object with a type information included.
  21. /// So, it can be deserialized using <see cref="DeserializeWithType"/> method later.
  22. /// </summary>
  23. public static string SerializeWithType(object obj, Type type)
  24. {
  25. var serialized = obj.ToJsonString();
  26. return string.Format(
  27. "{0}{1}{2}",
  28. type.AssemblyQualifiedName,
  29. TypeSeperator,
  30. serialized
  31. );
  32. }
  33. /// <summary>
  34. /// Deserializes an object serialized with <see cref="SerializeWithType(object)"/> methods.
  35. /// </summary>
  36. public static T DeserializeWithType<T>(string serializedObj)
  37. {
  38. return (T)DeserializeWithType(serializedObj);
  39. }
  40. /// <summary>
  41. /// Deserializes an object serialized with <see cref="SerializeWithType(object)"/> methods.
  42. /// </summary>
  43. public static object DeserializeWithType(string serializedObj)
  44. {
  45. var typeSeperatorIndex = serializedObj.IndexOf(TypeSeperator);
  46. var type = Type.GetType(serializedObj.Substring(0, typeSeperatorIndex));
  47. var serialized = serializedObj.Substring(typeSeperatorIndex + 1);
  48. var options = new JsonSerializerSettings
  49. {
  50. ContractResolver = new AbpCamelCasePropertyNamesContractResolver()
  51. };
  52. return JsonConvert.DeserializeObject(serialized, type, options);
  53. }
  54. }
  55. }