从 Newtonsoft 的 JSON 序列化器解析 JSON 日期时间 [英] Parsing JSON DateTime from Newtonsoft's JSON Serializer

查看:29
本文介绍了从 Newtonsoft 的 JSON 序列化器解析 JSON 日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Newtonsoft 的 JSON 序列化器序列化了一个对象,并且 DateTime 已经通过:

I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:

/Date(1237588418563+0000)/

当我对其进行 $.evalJSON() 时,它是一个对象,但我在其上找不到任何正常的 Date 方法,例如 toUTCString.

When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.

任何想法我可以用这个做什么?

Any ideas what I can do with this?

推荐答案

使用 Json.NET 附带的其中一个 JsonConverter 来处理日期以获得更好的格式.JavaScriptDateTimeConverter 会自动给你一个 JavaScript 日期.

Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.

public class LogEntry    
{    
  public string Details { get; set; }    
  public DateTime LogDate { get; set; }
}

[Test]
public void WriteJsonDates()
{    
  LogEntry entry = new LogEntry    
  {    
    LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),    
    Details = "Application started."    
  };    


  string defaultJson = JsonConvert.SerializeObject(entry);    
  // {"Details":"Application started.","LogDate":"/Date(1234656000000)/"}     

  string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());    
  // {"Details":"Application started.","LogDate":new Date(1234656000000)}

  string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());    
  // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}    
}

文档:序列化日期JSON 与 Json.NET

这篇关于从 Newtonsoft 的 JSON 序列化器解析 JSON 日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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