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.

2
  • 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. Commented Apr 18, 2013 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 :) Commented Apr 19, 2013 at 9:38

2 Answers 2

43

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") );
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot Man, but i am getting an error about ReadJson method not implemented
Since you said i just want to send the value as "day/month/year" string on response I only implemented WriteJson
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"
Hi Again, Fixed the issue by using ParseExact :)
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? stackoverflow.com/questions/60648268/how-to-set-globalization
8

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

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateTimeConvertor())

1 Comment

makes great for me! Make sure you are adding this converter at the global config (WebApiConfig) , not at the help area (HelpPageConfig)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.