Matt Whetton Matt Whetton - 2 months ago 19
C# Question

Ignoring an invalid field when deserializing json in Json.Net

I'm trying to deserialize some json from a 3rd party provider, and occasionally it returns some invalid date field (like -0001-01-01 or something). This causes the process to throw an exception.

Is there a way to tell Json.Net to ignore fields that are invalid?

Thanks

Matt

Answer

To expand on the answer from David, I have used a custom DateTime converter:

public class SafeDateTimeConvertor : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        DateTime result;
        if (DateTime.TryParse(reader.Value.ToString(), out result))
            return result;
        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd hh:mm:ss"));
    }
}

Which is then applied like this:

var result = JsonConvert.DeserializeObject<TestClass>(json, new SafeDateTimeConvertor());
Comments