JSON.NET: Unknown element handling during deserialization

I use JSON for data exchange. And I use the JSON.NET framework.

I have a class:

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

And I have the following code:

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

Since there is no "Mileage" field in the CarEntity class, I need to warn about this warning:

Unknown field: Mileage = 35000

Is there any way to do this?

+6
source share
1 answer

It is a little complicated, but you can. Change your code to:

 var parsed = (CarEntity)JsonConvert.DeserializeObject(jsonString, typeof(CarEntity), new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error, Error = ErrorHandler }); 

And add:

 private static void ErrorHandler(object x, ErrorEventArgs error) { Console.WriteLine(error.ErrorContext.Error); error.ErrorContext.Handled = true; } 

You should probably do more with the last line, because now every error does not throw an exception.

UPDATE

Decompiled code throwing an exception in 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(); 
+7
source

All Articles