2013-04-12 22 views
6

我正在使用JSON進行數據交換。我正在使用JSON.NET框架。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

有沒有辦法做到這一點?

回答

7

這是有點棘手,但你可以。你的代碼更改爲:

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; 
} 

你或許應該在最後一行做多,因爲現在每個錯誤不會拋出異常。

UPDATE

反編譯的代碼形式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(); 
+0

不要工作。引發了JsonSerializationException,並且省略了ErrorHandler。 – wishmaster

+0

完整的代碼在這裏:http://pastebin.com/zjztsZDx。如果您有問題,請告訴我您的代碼 –

+0

好的,謝謝。這是JSON.NET版本4.0的問題。當我更新到5.0版時,ErrorHandler被調用。但仍然沒有解決我的問題。我怎麼知道未知的成員是錯誤的原因?我有一個異常消息:「找不到'CarEntity'類型對象的成員'Mileage'...」但解析消息是不可接受的。 – wishmaster