当前位置: 欣欣网 > 码农

Newtonsoft.Json/Json.NET忽略序列化时的意外错误

2024-03-23码农

在.NET中Newtonsoft.Json(Json.NET)是我们常用来进行Json序列化与反序列化的库。

而在使用中常会遇到反序列化Json时,遇到不规则的Json数据解构而抛出异常。

Newtonsoft.Json 支持序列化和反序列化过程中的错误处理。

允许您捕获错误并选择是处理它并继续序列化,还是让错误冒泡并抛出到您的应用程序中。

错误处理是通过两种方法定义的:JsonSerializerSettings 上的ErrorEvent和OnErrorAttribute。

ErrorEvent

下面是个ErrorEvent的例子,下面的例子中我们既能正确反序列化列表中的事件类型,也能捕获其中的错误事件

List<string> errors = new List<string>();List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[ '2009-09-09T00:00:00Z', 'I am not a date and will error!', [ 1 ], '1977-02-20T00:00:00Z', null, '2000-12-01T00:00:00Z' ]",new JsonSerializerSettings { Error = delegate(object sender, ErrorEventArgs args) { errors.Add(args.ErrorContext.Error.Message); args.ErrorContext.Handled = true; }, Converters = { new IsoDateTimeConverter() } });// 2009-09-09T00:00:00Z// 1977-02-20T00:00:00Z// 2000-12-01T00:00:00Z

OnErrorAttribute

OnErrorAttribute的工作方式与 Newtonsoft.Json 的其他.NET 序列化属性非常相似。

您只需将该属性放置在采用正确参数的方法上:StreamingContext 和 ErrorContext。方法的名称并不重要。

public classPersonError{private List<string> _roles;publicstring Name { get; set; }publicint Age { get; set; }public List<string> Roles {get {if (_roles == null) {thrownew Exception("Roles not loaded!"); }return _roles; }set { _roles = value; } }publicstring Title { get; set; } [OnError]internalvoidOnError(StreamingContext context, ErrorContext errorContext) { errorContext.Handled = true; }}PersonError person = new PersonError{ Name = "George Michael Bluth", Age = 16, Roles = null, Title = "Mister Manager"};string json = JsonConvert.SerializeObject(person, Formatting.Indented);Console.WriteLine(json);//{// "Name": "George Michael Bluth",// "Age": 16,// "Title": "Mister Manager"//}

关注获取技术分享