这有点棘手,但你可以。将您的代码更改为:
var parsed = (CarEntity)JsonConvert.DeserializeObject(jsonString, typeof(CarEntity), new JsonSerializerSettings()
{
MissingMemberHandling = MissingMemberHandling.Error,
Error = ErrorHandler
});
并添加:
private static void ErrorHandler(object x, ErrorEventArgs error)
{
Console.WriteLine(error.ErrorContext.Error);
error.ErrorContext.Handled = true;
}
您可能应该对最后一行做更多的事情,因为现在每个错误都不会引发异常。
更新
在 Json.NET 中调用异常的反编译代码表单:
if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Verbose)
this.TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("Could not find member '{0}' on {1}", (IFormatProvider) CultureInfo.InvariantCulture, (object) propertyName, (object) contract.UnderlyingType)), (Exception) null);
if (this.Serializer.MissingMemberHandling == MissingMemberHandling.Error)
throw JsonSerializationException.Create(reader, StringUtils.FormatWith("Could not find member '{0}' on object of type '{1}'", (IFormatProvider) CultureInfo.InvariantCulture, (object) propertyName, (object) contract.UnderlyingType.Name));
reader.Skip();