beagreatman

导航

 

DateTime转换成json的时候容易出现不想要的格式,在网上搜索了相关的解决方法copy如下:

参考http://www.newtonsoft.com/json/help/html/DatesInJSON.htm

public class LogEntry
 {
     public string Details { get; set; }
     public DateTime LogDate { get; set; }
 }
 
public void WriteJsonDates()
 {
     LogEntry entry = new LogEntry
   {
        LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
        Details = "Application started."
    };

    // default as of Json.NET 4.5
    string isoJson = JsonConvert.SerializeObject(entry);
    // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}

    JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  };
    string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
    // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}

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

posted on 2015-12-03 09:43  BeAMan  阅读(1594)  评论(0编辑  收藏  举报