的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.
但我怎么能输出自己的自定义DateTime格式字符串,如:DD / MM / YYYY HH:MM。
But how can i output my own custom dateTime format string ,like :"dd/MM/yyyy hh:mm".
我可以在MVC3堵Json.NET作为默认的序列化时,这样做,但不能似乎做它在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;
和定制转换器我试图impliment是像这样:
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将AP preciated:)
Anyhelp would be appreciated :)
推荐答案
更改设置,设置code是这样的:
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;
在您的code你只是改变局部变量的值。
In your code you are just changing local variable value.
这篇关于的WebAPI Json.NET定制的日期处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!