123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- using System;
- using System.IO;
- using System.Text.Json;
- namespace DownloadImagesTool
- {
- /// <summary>
- /// This is a utilities class for json serializer and deserializer.
- /// </summary>
- public class JsonHelper
- {
- /// <summary>
- /// Deserializer from json result.
- /// </summary>
- /// <typeparam name="T">Type of object.</typeparam>
- /// <param name="jsonResult">Json string</param>
- /// <returns>Instance of T.</returns>
- public static T DeserializerJson<T>(string jsonResult, JsonSerializerOptions jsonSerializerOptions = null) where T : class
- {
- return JsonSerializer.Deserialize(jsonResult, typeof(T), jsonSerializerOptions) as T;
- }
- /// <summary>
- /// Deserializer from object result.
- /// </summary>
- /// <typeparam name="T">Type of object.</typeparam>
- /// <param name="jsonResult">Json string</param>
- /// <returns>Instance of T.</returns>
- public static T DeserializerObject<T>(object jsonObj, JsonSerializerOptions jsonSerializerOptions = null) where T : class
- {
- var jsonDoc = JsonDocument.Parse(SerializerToJson(jsonObj));
- return DeserializerJson<T>(jsonDoc.RootElement.GetRawText(), jsonSerializerOptions);
- }
- /// <summary>
- /// Serialize from instance to json string
- /// </summary>
- /// <typeparam name="T">Type of object.</typeparam>
- /// <param name="instance">Instance need to serialize.</param>
- /// <param name="useJsonFormatter"></param>
- /// <returns>The json string</returns>
- public static string SerializerToJson<T>(T instance, JsonSerializerOptions jsonSerializerOptions = null)
- {
- return JsonSerializer.Serialize(instance, jsonSerializerOptions);
- }
- /// <summary>
- /// Deserializer json to object with json file
- /// </summary>
- /// <typeparam name="T">Convert type</typeparam>
- /// <param name="jsonFilePath">Json file path</param>
- /// <returns></returns>
- public static T DeserializerJsonFile<T>(string jsonFilePath, JsonSerializerOptions jsonSerializerOptions = null) where T : class
- {
- try
- {
- using (var stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- using (var sr = new StreamReader(stream))
- {
- return DeserializerJson<T>(sr.ReadToEnd(), jsonSerializerOptions);
- }
- }
- }
- catch (Exception exception)
- {
- Console.WriteLine($"JsonHelper_DeserializerJsonFile error:{exception}");
- return default(T);
- }
- }
- }
- }
|