I'm trying unsuccessfully to create custom DateTime converter. The problem: I have many objects to serialize, some of the containing property of DateTime with DateTime.MinValue in it. I want to serialize it as null. But all the solution that I foud asking to decorate the proper inside the object (I can't do it) Other solution that I found below, is to create converter, As far as I can understand, this convertor works only DateTime object returned explicitly and not inside other object. Please help.
public class DateTimeConverter : JsonConverter
{
private readonly Type[] types;
public DateTimeConverter(params Type[] types)
{
this.types = types;
}
public override bool CanConvert(Type objectType)
{
return types.Any(t => t == objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
if (value is DateTime && value.Equals(DateTime.MinValue))
{
t = JToken.FromObject(null);
t.WriteTo(writer);
}
else
{
t.WriteTo(writer);
}
}
else
{
if (value.Equals(DateTime.MinValue)) {
t = JToken.FromObject(null);
t.WriteTo(writer);
}
else {
t.WriteTo(writer);
}
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}