JSON.处理反序列化的未知成员
本文关键字:未知 成员 反序列化 处理 JSON | 更新日期: 2023-09-27 18:08:43
我使用JSON进行数据交换。我用的是JSON。净框架。
我有一个类:
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));
}
由于在entity类中没有"里程"字段,我需要日志警告:
未知字段:里程=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中调用异常的反编译代码。净:
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();