Using a custom JSON formatter for Web API 2

非 Y 不嫁゛ 提交于 2019-12-11 05:53:01

问题


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:


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());


来源:https://stackoverflow.com/questions/41629523/using-a-custom-json-formatter-for-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!