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?

推荐答案

使用Json.NET附带的JsonConverter之一来处理日期,以获得更好的格式.JavaScriptDateTimeConverter将自动为您提供JavaScript日期.

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

文件:Serializing Dates in JSON with Json.NET

Json相关问答推荐

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

如何在数组抖动中按值分组

在PowerShell中,如何获取数据对所在的JSON对象的名称

序列化从/到空值

重构JOLT代码以获得预期输出

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

jq json - 按键名 Select

我需要在 mongodb compass 中检索索引(编号 1)信息

如何将动态复杂 json 解析为dart 对象或模型

杰克逊 2.0 和 Spring 3.1

将 js Array() 转换为 JSON 对象以用于 JQuery .ajax

如何使用法语口音对数组进行 json_encode?

如何将 LinkedTreeMap 转换为 gson JsonObject

关于使用 $ref 的 JSON 模式

如何向(JSON)对象的原型添加方法?

如何在 Django JSONField 数据上聚合(最小/最大等)?

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

带有 Jackson 的不可变 Lombok 注释类

如何向 json IAM 策略添加 comments ?

jq:按属性分组和键