86 lines
2.1 KiB
C#
86 lines
2.1 KiB
C#
using MasstransferCommon.Convert;
|
|
using Newtonsoft.Json;
|
|
|
|
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);
|
|
}
|
|
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
|
|
{
|
|
var settings = new JsonSerializerSettings
|
|
{
|
|
NullValueHandling = NullValueHandling.Ignore,
|
|
};
|
|
settings.Converters.Add(new DatetimeConverter());
|
|
|
|
return JsonConvert.DeserializeObject<T>(json, settings);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(e);
|
|
throw new ArgumentException($" 无效的json 字符串 {json} ");
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
} |