对Web API 2使用自定义JSON格式化程序 [英] Using a custom JSON formatter for Web API 2

查看:172
本文介绍了对Web API 2使用自定义JSON格式化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义JSON格式程序,该格式程序从DateTime值中删除了时间戳.以下是代码:

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;

当我使用该格式化程序时,由于我的WebApiConfig文件中存在JSON.Net格式化程序,因此上述格式化程序对该字符串进行了两次序列化.以下是JSON.Net格式化程序的代码:

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

当我删除JSON.Net格式化程序并使用我的自定义格式化程序时,JSON被序列化一次,但是被嵌入到XML中.

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

如何在不将JSON嵌入XML的情况下删除JSON.Net格式化程序并使用自定义格式化程序?

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

推荐答案

Web API不会两次将字符串转换为Json,除非您告知它,也不会使用XML.尽管您没有提供任何代码,所以无法说出这些问题中的每一个为什么发生.

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.

解决原始问题,将DateTime属性仅序列化为日期非常容易.只需创建一个自定义转换器,然后通过属性将其应用到所需的属性即可. Json.NET的 JSON序列化日期中对此进行了描述.您可以在这个可能重复的SO问题中找到实际的实现 .

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" });

或使用自定义转换器:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new OnlyDateConverter());

这篇关于对Web API 2使用自定义JSON格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆