wishmaster wishmaster - 1 year ago 102
JSON Question

JSON.NET: Unknown members handling on deserialization

I'm using JSON for data interchange. And I'm using JSON.NET framework.

I have the class:

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

And I have 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 are no "Mileage" field in CarEntity class I need log warning about it:

Unknown field: Mileage=35000

Is there some way to do it?

Answer Source

It is little tricky 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)
    error.ErrorContext.Handled = true;

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


Decompiled code form invoking 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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download