Dispenser/DispenserCommon/Utils/JsonUtil.cs

68 lines
1.5 KiB
C#

using Newtonsoft.Json;
using Serilog;
namespace DispenserCommon.Utils;
public class JsonUtil
{
public static string ToJson(object obj)
{
try
{
return JsonConvert.SerializeObject(obj);
}
catch (Exception e)
{
throw new ArgumentException($" 无效的json 对象 {obj} ");
}
}
public static Dictionary<string, object>? ToDictionary(string json)
{
try
{
return JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
catch (Exception e)
{
throw new ArgumentException($" 无效的json 对象 {json} ");
}
}
public static T FromJson<T>(string json)
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception e)
{
Log.Error($"json解析异常 {e.Message}");
return default;
}
}
public static object? FromJson(Type type, string json)
{
try
{
return JsonConvert.DeserializeObject(json, type);
}
catch (Exception e)
{
throw new ArgumentException($" 无效的json 字符串 {json} ");
}
}
public static T FromJsonOrDefault<T>(string json)
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception e)
{
return default;
}
}
}