asp.net-mvc-4 – WebApi Json.NET自定义日期处理

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-4 – WebApi Json.NET自定义日期处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我全球明确地配置了我的MVC4应用程序来使用 JSON.NET序列化程序.我知道在序列化日期时可以选择使用ISO标准日期或旧的Microsoft日期格式.

但是如何输出我自己的customTime格式的字符串,如:“dd / MM / yyyy hh:mm”.

当插入Json.NET作为默认序列化程序时,我可以在MVC3中执行此操作,但似乎无法在MVC4中执行此操作.

到目前为止在application_start我已经做了:

  1. var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
  2. JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
  3. {
  4. Formatting = Formatting.Indented,DateTimeZoneHandling = DateTimeZoneHandling.Utc,};
  5. jSettings.Converters.Add(new MyDateTimeConvertor() );
  6. settings = jSettings;

和我试图暗示的自定义转换器是这样的:

  1. public class MyDateTimeConvertor : DateTimeConverterBase
  2. {
  3. public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer)
  4. {
  5. return DateTime.Parse(reader.Value.ToString());
  6. }
  7.  
  8. public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer)
  9. {
  10. writer.WriteValue(((DateTime)value).ToString("dd/MM/yyyy hh:mm"));
  11. }
  12. }

Anyhelp将不胜感激:)

解决方法

更改您的设置设置代码如下所示:
  1. JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
  2. JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings()
  3. {
  4. Formatting = Formatting.Indented,DateTimeZoneHandling = DateTimeZoneHandling.Utc
  5. };
  6. jSettings.Converters.Add(new MyDateTimeConvertor());
  7. jsonFormatter.SerializerSettings = jSettings;

在你的代码中,你只是改变局部变量值.

猜你在找的asp.Net相关文章