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?

1
  • 1
    Why are you trying to replace the converter globally instead of applying the converter attribute to the date-only properties? This similar question shows how easy it is to just add eg [JsonConverter(typeof(OnlyDateConverter))] to a property Commented Jan 13, 2017 at 7:48

1 Answer 1

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

1 Comment

Thanks for your various solutions. I went the config route and it worked great.

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.