Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET: Unknown members handling on deserialization

Tags:

json

c#

json.net

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?

like image 830
wishmaster Avatar asked Apr 12 '13 10:04

wishmaster


1 Answers

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)
{
    Console.WriteLine(error.ErrorContext.Error);
    error.ErrorContext.Handled = true;
}

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

UPDATE

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));
reader.Skip();
like image 172
Piotr Stapp Avatar answered Oct 06 '22 01:10

Piotr Stapp