JsonExtensions.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using JetBrains.Annotations;
  2. using Newtonsoft.Json;
  3. using System;
  4. namespace Abp.Json
  5. {
  6. public static class JsonExtensions
  7. {
  8. /// <summary>
  9. /// Converts given object to JSON string.
  10. /// </summary>
  11. /// <returns></returns>
  12. public static string ToJsonString(this object obj, bool camelCase = false, bool indented = false)
  13. {
  14. var settings = new JsonSerializerSettings();
  15. if (camelCase)
  16. {
  17. settings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver();
  18. }
  19. else
  20. {
  21. settings.ContractResolver = new AbpContractResolver();
  22. }
  23. if (indented)
  24. {
  25. settings.Formatting = Formatting.Indented;
  26. }
  27. return ToJsonString(obj, settings);
  28. }
  29. /// <summary>
  30. /// Converts given object to JSON string using custom <see cref="JsonSerializerSettings"/>.
  31. /// </summary>
  32. /// <returns></returns>
  33. public static string ToJsonString(this object obj, JsonSerializerSettings settings)
  34. {
  35. return obj != null
  36. ? JsonConvert.SerializeObject(obj, settings)
  37. : default(string);
  38. }
  39. /// <summary>
  40. /// Returns deserialized string using default <see cref="JsonSerializerSettings"/>
  41. /// </summary>
  42. /// <typeparam name="T"></typeparam>
  43. /// <param name="value"></param>
  44. /// <returns></returns>
  45. public static T FromJsonString<T>(this string value)
  46. {
  47. return value.FromJsonString<T>(new JsonSerializerSettings());
  48. }
  49. /// <summary>
  50. /// Returns deserialized string using custom <see cref="JsonSerializerSettings"/>
  51. /// </summary>
  52. /// <typeparam name="T"></typeparam>
  53. /// <param name="value"></param>
  54. /// <param name="settings"></param>
  55. /// <returns></returns>
  56. public static T FromJsonString<T>(this string value, JsonSerializerSettings settings)
  57. {
  58. return value != null
  59. ? JsonConvert.DeserializeObject<T>(value, settings)
  60. : default(T);
  61. }
  62. /// <summary>
  63. /// Returns deserialized string using explicit <see cref="Type"/> and custom <see cref="JsonSerializerSettings"/>
  64. /// </summary>
  65. /// <param name="value"></param>
  66. /// <param name="type"></param>
  67. /// <param name="settings"></param>
  68. /// <returns></returns>
  69. public static object FromJsonString(this string value, [NotNull] Type type, JsonSerializerSettings settings)
  70. {
  71. if (type == null)
  72. {
  73. throw new ArgumentNullException(nameof(type));
  74. }
  75. return value != null
  76. ? JsonConvert.DeserializeObject(value, type, settings)
  77. : null;
  78. }
  79. }
  80. }