2024-09-06 07:08:32 +00:00
|
|
|
|
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
|
|
|
|
|
{
|
2024-09-06 07:08:32 +00:00
|
|
|
|
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} ");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-05 11:41:09 +00:00
|
|
|
|
public static T? FromJson<T>(string json)
|
2024-06-03 08:35:49 +00:00
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2024-09-05 11:41:09 +00:00
|
|
|
|
var settings = new JsonSerializerSettings
|
|
|
|
|
{
|
2024-09-06 07:08:32 +00:00
|
|
|
|
NullValueHandling = NullValueHandling.Ignore,
|
2024-09-05 11:41:09 +00:00
|
|
|
|
};
|
2024-09-06 07:08:32 +00:00
|
|
|
|
settings.Converters.Add(new DatetimeConverter());
|
|
|
|
|
|
2024-09-05 11:41:09 +00:00
|
|
|
|
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
|
|
|
|
|
{
|
2024-09-06 07:08:32 +00:00
|
|
|
|
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} ");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-05 11:41:09 +00:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|