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

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

问题描述

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

  / Date(1237588418563 +0000)/ 

当我$ .evalJSON()时,它是一个对象,但我可以没有找到任何正常的Date方法,比如toCetring。



任何想法我可以做什么?

解决方案

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

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

[测试]
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 ,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}
}
/ pre>

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


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

/Date(1237588418563+0000)/

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?

解决方案

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"}    
}

Documentation: Serializing Dates in JSON with Json.NET

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

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