12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using System;
- using System.Text.Json;
- using Vinno.IUS.Common.Log;
- namespace Vinno.FIS.Sonopost.Helpers
- {
- public static class JsonHelper
- {
- /// <summary>
- /// convert object to json
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="options"></param>
- /// <returns></returns>
- public static string ToJson(object obj, JsonSerializerOptions options = null)
- {
- try
- {
- return JsonSerializer.Serialize(obj, options);
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"JsonHelper To Json {obj} Error:{ex}");
- return string.Empty;
- }
- }
- /// <summary>
- /// convert json to object
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="jsonStr"></param>
- /// <param name="options"></param>
- /// <returns></returns>
- public static T JsonToObj<T>(string jsonStr, JsonSerializerOptions options = null)
- {
- if (string.IsNullOrWhiteSpace(jsonStr))
- {
- return default;
- }
- try
- {
- return JsonSerializer.Deserialize<T>(jsonStr, options);
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"JsonHelper JsonToObj {jsonStr} Error:{ex}");
- return default;
- }
- }
- /// <summary>
- /// convert json to object
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="jsonStr"></param>
- /// <param name="options"></param>
- /// <returns></returns>
- public static object JsonToObj(string jsonStr, Type type, JsonSerializerOptions options = null)
- {
- if (string.IsNullOrWhiteSpace(jsonStr))
- {
- return default;
- }
- try
- {
- return JsonSerializer.Deserialize(jsonStr, type, options);
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"JsonHelper JsonToObj {jsonStr} Error:{ex}");
- return default;
- }
- }
- }
- }
|