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? ToDictionary(string json) { try { return JsonConvert.DeserializeObject>(json); } catch (Exception e) { throw new ArgumentException($" 无效的json 对象 {json} "); } } public static T? FromJson(string json) { try { var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, }; settings.Converters.Add(new DatetimeConverter()); return JsonConvert.DeserializeObject(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(string json) { try { return JsonConvert.DeserializeObject(json); } catch (Exception e) { return default; } } }