4

I'm using web API help documentation to connect API devs and UI client devs. One of the item I would like to define in the help is the Date format. And want it to be customized within the sample of request/response information at the API action details page:

I have request entity:

public class Request
{
    public string Id {get;set;}
    public string Type {get;set;}
    public DateTime Date {get;set;} 
}

This is a default representation at the help page:

{
  "Id": "sample string 1",
  "Type": "sample string 2",
  "Date": "2014-08-12T19:33:09.6221727+00:00"
}

I want it to be like the following:

{
  "Id": "sample string 1",
  "Type": "sample string 2",
  "Date": "08/13/2014"
}

How can I achieve this goal?

0

1 Answer 1

3

It turned out that ASP.NET Web.API uses the common Json.NET formatter and you can register your own date converter for this purposes:

   public class MyDateFormatConverter : DateTimeConverterBase
    {
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            return DateTime.Parse(reader.Value.ToString());
        }

        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString("d"));
        }
    }

and then register it at the GLOBAL (WebApiConfig, not HelpPageConfig) config:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new MyDateFormatConverter());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.