7

我正在使用 JSON 进行数据交换。我正在使用 JSON.NET 框架。

我有课:

public class CarEntity
{
    public string Model { get; set; }
    public int Year { get; set; }
    public int Price { get; set; }
}

我有以下代码:

public void Test()
{
    var jsonString = 
    @"{
      ""Model"": ""Dodge Caliber"",
      ""Year"": 2011,
      ""Price"": 15000,
      ""Mileage"": 35000
    }";
    var parsed = (CarEntity)JsonConvert.DeserializeObject(jsonString, typeof(CarEntity));
}

由于 CarEntity 类中没有“里程”字段,我需要有关它的日志警告:

未知字段:里程=35000

有什么办法吗?

4

1 回答 1

9

这有点棘手,但你可以。将您的代码更改为:

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();
于 2013-04-12T10:39:16.813 回答