我全球明确地配置了我的MVC4应用程序来使用
JSON.NET序列化程序.我知道在序列化日期时可以选择使用ISO标准日期或旧的Microsoft日期格式.
但是如何输出我自己的customTime格式的字符串,如:“dd / MM / yyyy hh:mm”.
当插入Json.NET作为默认序列化程序时,我可以在MVC3中执行此操作,但似乎无法在MVC4中执行此操作.
到目前为止在application_start我已经做了:
- 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;
和我试图暗示的自定义转换器是这样的:
- 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将不胜感激:)
解决方法
更改您的设置设置代码如下所示:
- 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;
在你的代码中,你只是改变局部变量值.