MasstransferExporter/MasstransferCommon/Utils/JsonUtil.cs

86 lines
2.1 KiB
C#
Raw Normal View History

using MasstransferCommon.Convert;
using Newtonsoft.Json;
2024-06-03 08:35:49 +00:00
namespace MasstransferCommon.Utils;
public class JsonUtil
{
public static string ToJson(object obj)
{
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
};
settings.Converters.Add(new DatetimeConverter());
return JsonConvert.SerializeObject(obj, settings);
2024-06-03 08:35:49 +00:00
}
catch (Exception e)
{
throw new ArgumentException($" 无效的json 对象 {obj} ");
}
}
2024-06-19 07:53:34 +00:00
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)
2024-06-03 08:35:49 +00:00
{
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
};
settings.Converters.Add(new DatetimeConverter());
return JsonConvert.DeserializeObject<T>(json, settings);
2024-06-03 08:35:49 +00:00
}
catch (Exception e)
{
2024-09-10 11:25:18 +00:00
Console.WriteLine(e);
2024-06-03 08:35:49 +00:00
throw new ArgumentException($" 无效的json 字符串 {json} ");
}
}
2024-06-19 11:28:48 +00:00
public static object? FromJson(Type type, string json)
{
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
};
settings.Converters.Add(new DatetimeConverter());
return JsonConvert.DeserializeObject(json, type, settings);
2024-06-19 11:28:48 +00:00
}
catch (Exception e)
{
throw new ArgumentException($" 无效的json 字符串 {json} ");
}
}
public static T? FromJsonOrDefault<T>(string json)
2024-06-03 08:35:49 +00:00
{
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception e)
{
return default;
}
}
}