WebApi Json.NET 自定义日期处理 [英] WebApi Json.NET custom date handling
问题描述
我已全局显式配置我的 MVC4 应用程序以使用 JSON.NET 序列化程序.我知道在序列化日期时我可以选择使用 ISO 标准日期或旧的 Microsoft 日期格式.
I have globally explicitly configured my MVC4 app to use the JSON.NET serializer . I know i have the choice of using the ISO standard dates or the old Microsoft date format when serializing dates.
但是我如何输出我自己的自定义日期时间格式字符串,比如:dd/MM/yyyy hh:mm".
But how can i output my own custom dateTime format string ,like :"dd/MM/yyyy hh:mm".
在插入 Json.NET 作为默认序列化程序时,我可以在 MVC3 中执行此操作,但在 MVC4 中似乎无法执行此操作.
I could do this in MVC3 when plugging in Json.NET as the default serializer but cant seem to do it in MVC4 .
到目前为止在 application_start 中我已经完成了:
So far in the application_start i have done :
var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
Formatting = Formatting.Indented,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
};
jSettings.Converters.Add(new MyDateTimeConvertor() );
settings = jSettings;
我试图实现的自定义转换器是这样的:
and the custom converter i tried to impliment is like so :
public class MyDateTimeConvertor : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.Parse(reader.Value.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString("dd/MM/yyyy hh:mm"));
}
}
任何帮助将不胜感激:)
Anyhelp would be appreciated :)
推荐答案
像这样更改您的设置设置代码:
Change your setting set up code like this:
JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
Formatting = Formatting.Indented,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
jSettings.Converters.Add(new MyDateTimeConvertor());
jsonFormatter.SerializerSettings = jSettings;
在您的代码中,您只是在更改局部变量值.
In your code you are just changing local variable value.
这篇关于WebApi Json.NET 自定义日期处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!