23

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.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
DevMania
  • 2,311
  • 4
  • 25
  • 43
  • 1
    L.B.'s answer gives you what you asked for, but please be very careful about how you use this. The reason we use ISO dates is because they are unambiguous and culture invariant. If you send your values as day/month/year, say a value like `1/4/2013` - Someone not aware of your locale might interpret that as January 4th, instead of the April 1st that you intended. – Matt Johnson-Pint Apr 18 '13 at 17:12
  • @Matt Johnson, thanks for reply, i totally agree with you 100%. this is an old thread and i only use ISO Date now and manipulate it at the client :) – DevMania Apr 19 '13 at 09:38

2 Answers2

42

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") );
    }
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Thanks a lot Man, but i am getting an error about ReadJson method not implemented – DevMania Dec 26 '11 at 22:15
  • Since you said `i just want to send the value as "day/month/year" string on response` I only implemented `WriteJson` – L.B Dec 26 '11 at 22:25
  • man thanks alot, it is working but i always get 01/01/0001 as result ,even that for example my DB record date is for example "2011-12-27T13:13:45.7052459Z" – DevMania Dec 27 '11 at 14:31
  • Hi Again, Fixed the issue by using ParseExact :) – DevMania Jan 01 '12 at 11:31
  • I'm stuck in similar problem, even though I'm assigning current thread culture to fr-FR in a delegating handler, I can see when a debug point inside WriteJson method is hit, the culture is en-US. As a result, date time value is not coming in culture specific format. What might be the problem? https://stackoverflow.com/questions/60648268/how-to-set-globalization – Sk Shahnawaz-ul Haque Mar 12 '20 at 09:17
8

If you are using Web Api add the custom formatter to the configuration using:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor())
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
user3615720
  • 91
  • 1
  • 2
  • makes great for me! Make sure you are adding this converter at the global config (WebApiConfig) , not at the help area (HelpPageConfig) – Mando Aug 12 '14 at 20:36