Reputation: 6786
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
Upvotes: 1
Views: 4719
Reputation: 2571
It happens, third parties can neglect type safety in their JSON. I recommend you contact them. I had a scenario where a property was either a string array or "false". Json.NET didn't like this so as a temporary hack, I created this custom converter to ignore the deserialization exception:
public class IgnoreDataTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try { return JToken.Load(reader).ToObject(objectType); }
catch { }
return objectType.IsValueType ? Activator.CreateInstance(objectType) : null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
This "TryConvert" approach is not advised. Use it as a temporary solution after you send your thoughts to the designers of the originating JSON you are consuming.
Upvotes: 0
Reputation: 6786
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());
Upvotes: 5
Reputation: 2272
JSON.NET has numerous ways to control serialization. You might look at Conditional Property (De)Serialization for example.
There's an entire topic in the online docs on Serializing Dates.
You could write a custom converter; see the documentation for the Newtonsoft.Json.Converters namespace.
Upvotes: 1