1

I have a custom JSON formatter that removes the time stamp from a DateTime value. The following is the code:

var isoJson = JsonConvert.SerializeObject(value, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });
        return isoJson;

When I use that formatter, the string is serialized twice by the above formatter and because of JSON.Net formatter in my WebApiConfig file. The following is the code for the JSON.Net formatter:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

When I remove the JSON.Net formatter and use my custom one, the JSON is serialized once but it is embedded in XML.

How do I remove the JSON.Net formatter and use my custom formatter without having my JSON embedded in XML?

user1647160
  • 491
  • 1
  • 10
  • 25
  • 1
    Why are you trying to replace the converter globally instead of applying the converter attribute to the date-only properties? This [similar question](http://stackoverflow.com/questions/16320762/dates-without-time-in-asp-net-web-apis-json-output) shows how easy it is to just add eg `[JsonConverter(typeof(OnlyDateConverter))]` to a property – Panagiotis Kanavos Jan 13 '17 at 07:48

1 Answers1

2

Web API won't convert a string to Json twice, unless you tell it to, nor will it use XML. You don't provide any code though, so it's impossible to say why each of these problems occur.

Solving the original problem though, serializing DateTime properties as dates only, is very easy. Just create a custom converter and apply it through an attribute to the properties you want. This is described in Json.NET's Serializing Dates in JSON. You can find an actual implementation in this arguably duplicate SO question.

Copying from that question, create a converter:

public class OnlyDateConverter : IsoDateTimeConverter
{
    public OnlyDateConverter()
    {
         DateTimeFormat = "yyyy-MM-dd";
    }
}

and then apply it to any property you want to serialize as date-only:

public class MyClass
{
    ...
   [JsonConverter(typeof(OnlyDateConverter))]
   public DateTime MyDate{get;set;}
   ...
}

Another answer in the same question shows how to make the change globally through configuration:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" });

or, using the custom converter:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new OnlyDateConverter());
Community
  • 1
  • 1
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236