JsonHelper.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Text.Json;
  3. using Vinno.IUS.Common.Log;
  4. namespace Vinno.FIS.Sonopost.Helpers
  5. {
  6. public static class JsonHelper
  7. {
  8. /// <summary>
  9. /// convert object to json
  10. /// </summary>
  11. /// <param name="obj"></param>
  12. /// <param name="options"></param>
  13. /// <returns></returns>
  14. public static string ToJson(object obj, JsonSerializerOptions options = null)
  15. {
  16. try
  17. {
  18. return JsonSerializer.Serialize(obj, options);
  19. }
  20. catch (Exception ex)
  21. {
  22. Logger.WriteLineError($"JsonHelper To Json {obj} Error:{ex}");
  23. return string.Empty;
  24. }
  25. }
  26. /// <summary>
  27. /// convert json to object
  28. /// </summary>
  29. /// <typeparam name="T"></typeparam>
  30. /// <param name="jsonStr"></param>
  31. /// <param name="options"></param>
  32. /// <returns></returns>
  33. public static T JsonToObj<T>(string jsonStr, JsonSerializerOptions options = null)
  34. {
  35. if (string.IsNullOrWhiteSpace(jsonStr))
  36. {
  37. return default;
  38. }
  39. try
  40. {
  41. return JsonSerializer.Deserialize<T>(jsonStr, options);
  42. }
  43. catch (Exception ex)
  44. {
  45. Logger.WriteLineError($"JsonHelper JsonToObj {jsonStr} Error:{ex}");
  46. return default;
  47. }
  48. }
  49. /// <summary>
  50. /// convert json to object
  51. /// </summary>
  52. /// <typeparam name="T"></typeparam>
  53. /// <param name="jsonStr"></param>
  54. /// <param name="options"></param>
  55. /// <returns></returns>
  56. public static object JsonToObj(string jsonStr, Type type, JsonSerializerOptions options = null)
  57. {
  58. if (string.IsNullOrWhiteSpace(jsonStr))
  59. {
  60. return default;
  61. }
  62. try
  63. {
  64. return JsonSerializer.Deserialize(jsonStr, type, options);
  65. }
  66. catch (Exception ex)
  67. {
  68. Logger.WriteLineError($"JsonHelper JsonToObj {jsonStr} Error:{ex}");
  69. return default;
  70. }
  71. }
  72. }
  73. }