當前位置: 妍妍網 > 碼農

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"//}

關註獲取技術分享