JsonHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.IO;
  3. using System.Text.Json;
  4. namespace DownloadImagesTool
  5. {
  6. /// <summary>
  7. /// This is a utilities class for json serializer and deserializer.
  8. /// </summary>
  9. public class JsonHelper
  10. {
  11. /// <summary>
  12. /// Deserializer from json result.
  13. /// </summary>
  14. /// <typeparam name="T">Type of object.</typeparam>
  15. /// <param name="jsonResult">Json string</param>
  16. /// <returns>Instance of T.</returns>
  17. public static T DeserializerJson<T>(string jsonResult, JsonSerializerOptions jsonSerializerOptions = null) where T : class
  18. {
  19. return JsonSerializer.Deserialize(jsonResult, typeof(T), jsonSerializerOptions) as T;
  20. }
  21. /// <summary>
  22. /// Deserializer from object result.
  23. /// </summary>
  24. /// <typeparam name="T">Type of object.</typeparam>
  25. /// <param name="jsonResult">Json string</param>
  26. /// <returns>Instance of T.</returns>
  27. public static T DeserializerObject<T>(object jsonObj, JsonSerializerOptions jsonSerializerOptions = null) where T : class
  28. {
  29. var jsonDoc = JsonDocument.Parse(SerializerToJson(jsonObj));
  30. return DeserializerJson<T>(jsonDoc.RootElement.GetRawText(), jsonSerializerOptions);
  31. }
  32. /// <summary>
  33. /// Serialize from instance to json string
  34. /// </summary>
  35. /// <typeparam name="T">Type of object.</typeparam>
  36. /// <param name="instance">Instance need to serialize.</param>
  37. /// <param name="useJsonFormatter"></param>
  38. /// <returns>The json string</returns>
  39. public static string SerializerToJson<T>(T instance, JsonSerializerOptions jsonSerializerOptions = null)
  40. {
  41. return JsonSerializer.Serialize(instance, jsonSerializerOptions);
  42. }
  43. /// <summary>
  44. /// Deserializer json to object with json file
  45. /// </summary>
  46. /// <typeparam name="T">Convert type</typeparam>
  47. /// <param name="jsonFilePath">Json file path</param>
  48. /// <returns></returns>
  49. public static T DeserializerJsonFile<T>(string jsonFilePath, JsonSerializerOptions jsonSerializerOptions = null) where T : class
  50. {
  51. try
  52. {
  53. using (var stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  54. {
  55. using (var sr = new StreamReader(stream))
  56. {
  57. return DeserializerJson<T>(sr.ReadToEnd(), jsonSerializerOptions);
  58. }
  59. }
  60. }
  61. catch (Exception exception)
  62. {
  63. Console.WriteLine($"JsonHelper_DeserializerJsonFile error:{exception}");
  64. return default(T);
  65. }
  66. }
  67. }
  68. }