How to create a JSON.NET Date to String custom Converter
Could someone tell me please how I can create a custom converter
I know I can use JSON.NET ISODateConvertor, but what I want is specific, I just want to send the value as "day/month/year" string on response.
Solution 1:
Something like this?
string str = JsonConvert.SerializeObject(new DateTimeClass(), new MyDateTimeConvertor());
public class DateTimeClass
{
public DateTime dt;
public int dummy = 0;
}
public class MyDateTimeConvertor : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.Parse(reader.Value.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue( ((DateTime)value).ToString("dd/MM/yyyy") );
}
}
Solution 2:
If you are using Web Api add the custom formatter to the configuration using:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor())