MasstransferExporter/MasstransferCommon/Utils/JsonUtil.cs

66 lines
1.4 KiB
C#

using Newtonsoft.Json;
namespace MasstransferCommon.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)
{
throw new ArgumentException($" 无效的json 字符串 {json} ");
}
}
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;
}
}
}