如何反序列化Unix时间戳(微秒)为DateTime?

问题描述:

{
   "title":"Mozilla Firefox",
   "id":24,
   "parent":2,
   "dateAdded":1356753810000000,
   "lastModified":1356753810000000,
   "type":"text/x-moz-place-container",
   "children":[]
}

C#

class Bookmark
{
    public string title;
    public string id;
    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public DateTime dateAdded;
    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public DateTime lastModified;
    public string type;
    public string root;
    public long parent;
    public List<Bookmark> children;
}

private static void Main(string[] args)
{
    var json = File.ReadAllText(@"T:/bookmarks-2013-11-13.json");
    var bookmarks = JsonConvert.DeserializeObject<Bookmark>(json);
}

我得到当我尝试运行此异常,

I get an exception when I try running this,

更多信息:错误读取日期。意外令牌:整数。路径dateAdded

Additional information: Error reading date. Unexpected token: Integer. Path 'dateAdded'

我想通过使用 JavaScriptDateTimeConverter ,JSON.NET能弄清楚如何反序列化的UNIX时间戳(毫秒正弦纪元)。怎样做最简单的方法?

I thought by using the JavaScriptDateTimeConverter, JSON.NET could figure out how to deserialize those unix timestamps (ms sinc epoch). What's the easiest way to do this?

有麻烦的转换器查找文档......它可能不会太难写一个自己,如果必要的。

Having trouble finding documentation on the converters... it probably wouldn't be too hard to write one myself if necessary.

编辑:这些实际上是微秒,毫秒不

Those are actually microseconds, not milliseconds.

我清理克里斯的解决方案一点点实施 WriteJson

class Bookmark
{
    public string title;
    public long id;
    [JsonConverter(typeof(MicrosecondEpochConverter))]
    public DateTime dateAdded;
    [JsonConverter(typeof(MicrosecondEpochConverter))]
    public DateTime lastModified;
    public string type;
    public string root;
    public long parent;
    public List<Bookmark> children;
    public string uri;

    public override string ToString()
    {
        return string.Format("{0} - {1}", title, uri);
    }
}

public class MicrosecondEpochConverter : DateTimeConverterBase
{
    private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteRawValue(((DateTime)value - _epoch).TotalMilliseconds + "000");
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.Value == null) { return null; }
        return _epoch.AddMilliseconds((long)reader.Value / 1000d);
    }
}

internal class Program
{

    private static void Main(string[] args)
    {
        var jsonString = File.ReadAllText(@"T:/bookmarks-2013-11-13.json");
        var rootMark = JsonConvert.DeserializeObject<Bookmark>(jsonString);
        var ret = JsonConvert.SerializeObject(rootMark);
    }
}