我正在使用 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 类中没有“Mileage”字段,所以我需要记录有关它的警告:
Unknown field: Mileage=35000
有什么办法吗?
最佳答案
这有点棘手,但你可以。将您的代码更改为:
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();
关于c# - JSON.NET:处理反序列化的未知成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15968673/