例如我擁有以下代碼。
public class NewObject
{
public int? TestValue { get; set; }
public int? Age { get; set; }
}
當我為 TestValue 屬性傳入一個非法數據的時候,在使用 JSON.NET 進行反序列化時會拋出異常。例如我通過以下代碼對一個字符串進行反序列化,如果不出意外的話會提示無效參數值的異常。
var newValue = JsonConvert.DeserializeObject<NewObject>(@"{""TestValue"":""FFFF"",""Age"":15}",settings);
通過 Stackoverflow 查詢得知,可以通過在反序列化時指定 JsonSerializerSettings 對象進行忽略。
var settings = new JsonSerializerSettings
{
Error = (obj, args2) =>
{
args2.ErrorContext.Handled = true;
}
};
var newValue = JsonConvert.DeserializeObject<NewObject>(@"{""TestValue"":""FFFF"",""Age"":15}",settings);
這樣,在進行反序列化的時候就可以忽略 TestValue 的無效值,為其屬性設置為 null,並且成功解析 Age 的值。
如果你是 ASP.NET Core 的程序,可以通過 IServiceCollection 的 Configure<T>() 方法來配置 Error 的處理器。
services.Configure<MvcJsonOptions>(jsonOptions =>
{
// 忽略轉換過程中的異常信息
jsonOptions.SerializerSettings.Error += (sender, args) => { args.ErrorContext.Handled = true; };
});
