如何将unix时间戳(μ;s)从JSON反序列化为日期时间? JSON C# 类书签 { 公共字符串标题; 公共字符串id; [JsonProperty(ItemConverterType=typeof(JavaScriptDateTimeConverter))] 已添加公共日期时间; [JsonProperty(ItemConverterType=typeof(JavaScriptDateTimeConverter))] 上次修改的公共日期时间; 公共字符串类型; 公共字符串根; 公共长期父母; 公开儿童名单; } 私有静态void Main(字符串[]args) { var json=File.ReadAllText(@“T:/bookmarks-2013-11-13.json”); var bookmarks=JsonConvert.DeserializeObject(json); }

如何将unix时间戳(μ;s)从JSON反序列化为日期时间? JSON C# 类书签 { 公共字符串标题; 公共字符串id; [JsonProperty(ItemConverterType=typeof(JavaScriptDateTimeConverter))] 已添加公共日期时间; [JsonProperty(ItemConverterType=typeof(JavaScriptDateTimeConverter))] 上次修改的公共日期时间; 公共字符串类型; 公共字符串根; 公共长期父母; 公开儿童名单; } 私有静态void Main(字符串[]args) { var json=File.ReadAllText(@“T:/bookmarks-2013-11-13.json”); var bookmarks=JsonConvert.DeserializeObject(json); },c#,json.net,C#,Json.net,当我试着运行这个时,我遇到了一个异常 附加信息:读取日期时出错。意外标记:整数。路径“已添加日期” 我认为,通过使用JavaScriptDateTimeConverter,JSON.NET可以弄清楚如何反序列化这些unix时间戳(自epoch以来的毫秒)。最简单的方法是什么 在转换器上查找文档时遇到问题。。。如果有必要的话,我自己写一本可能不会太难 编辑:这些实际上是微秒,而不是毫秒。您可以创建自定义日期时间转换器 class Bookmark { public string title

当我试着运行这个时,我遇到了一个异常

附加信息:读取日期时出错。意外标记:整数。路径“已添加日期”

我认为,通过使用
JavaScriptDateTimeConverter
,JSON.NET可以弄清楚如何反序列化这些unix时间戳(自epoch以来的毫秒)。最简单的方法是什么

在转换器上查找文档时遇到问题。。。如果有必要的话,我自己写一本可能不会太难


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

您可以创建自定义日期时间转换器

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);
}
另一种方法是双重注释类成员

public class MyDateTimeConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(DateTime);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var t = long.Parse((string)reader.Value);
        return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

嗯……棘手的是DateTime构造函数不接受时间戳作为参数

本文提供了一个解决方案:

您必须调用此函数,最好在类中使用默认构造函数,或者在它的
get
方法中使用另一个属性返回此函数。

我清理了一个tad并实现了
WriteJson

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}
类书签
{
公共字符串标题;
公共长id;
[JsonConverter(类型(微秒转换器))]
已添加公共日期时间;
[JsonConverter(类型(微秒转换器))]
上次修改的公共日期时间;
公共字符串类型;
公共字符串根;
公共长期父母;
公开儿童名单;
公共字符串uri;
公共重写字符串ToString()
{
返回string.Format(“{0}-{1}”,标题,uri);
}
}
公共类微秒转换器:DateTimeConverterBase
{
私有静态只读日期时间_epoch=新日期时间(1970,1,1,0,0,0,DateTimeKind.Utc);
公共重写void WriteJson(JsonWriter编写器、对象值、JsonSerializer序列化器)
{
writer.WriteRawValue(((DateTime)value-_epoch).totalmillizes+“000”);
}
公共重写对象ReadJson(JsonReader阅读器,类型objectType,对象existingValue,JsonSerializer序列化程序)
{
如果(reader.Value==null){return null;}
返回_epoch.add毫秒((长)reader.Value/1000d);
}
}
内部课程计划
{
私有静态void Main(字符串[]args)
{
var jsonString=File.ReadAllText(@“T:/bookmarks-2013-11-13.json”);
var rootMark=JsonConvert.DeserializeObject(jsonString);
var ret=JsonConvert.SerializeObject(rootMark);
}
}

有一种内置方法可以将unix时间戳转换为DateTime,而无需编写自己的类:

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);
    }
}

中的注释不正确,因为
JavaScriptDateTimeConverter
用于
Date(52231943)
格式,而不是OP中的Unix时间戳


我意识到这个问题已经问了几年了,所以很有可能是因为这个问题而增加了这个类,但这可能会帮助任何遇到相同问题的人。

我就是这样做的,并且它起了作用

在我的ViewModel中 我有一个DateTime类型的公共属性

[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime lastModified;
在我的模型中,我有Long类型的公共属性,它以JSON格式从API获取日期

Public DateTime TimeToBeShown {get; set;}

我想根据公认的答案为.NETCore和
System.Text.Json
添加一个解决方案。 在撰写本文时已在3.1中验证。

公共类UnixDateTimeConverter:JsonConverter
{
公共覆盖日期时间读取(参考Utf8JsonReader reader,键入typeToConvert,JsonSerializerOptions选项)
{
return DateTime.UnixEpoch.AddSeconds(reader.GetInt64());
}
公共重写无效写入(Utf8JsonWriter编写器、日期时间值、JsonSerializerOptions选项)
{
writer.WriteStringValue((value-DateTime.UnixEpoch.totalmillizes+“000”);
}
}
然后,您可以使用数据注释应用它

[JsonConverter(typeof(UnixDateTimeConverter))]
公共日期时间MyDateTime{get;set;}

这看起来很有效。那么属性是用来做什么的呢?ItemConverterType用于转换数组中的项,尝试使用JsonProperty和JsonConverter对属性进行双重注释,比如[JsonProperty(PropertyName=“DateAdd”)][JsonConverter(typeof(JavaScriptDateTimeConverter))]不需要双重注释<代码>[JsonConverter]是我一直在寻找的属性。非常感谢。(但是
[JsonProperty]
也很好,因为现在我可以重命名我的属性)使用Convert.ToString(reader.Value)而不是本机对象cast(string)reader.Value来让它为我工作。我尝试了你的答案,但我也想使用设置来忽略null值。如何使用这两个值?当我像下面这样尝试时,我得到了一些无效的参数,它们是
JsonConvert.DeserializeObject(resresponse.Content,typeof(MyClass),新的JsonSerializerSettings{NullValueHandling=NullValueHandling.Ignore},新的MyDateTimeConverter())这是一个非常有价值的问题,因为unix times是唯一能够完全抵抗JS在时区方面的缺点的表示。很好的清理。您还可以将_epoch字段设置为静态,以增加一点内存消耗编辑的代码来处理
DateTime?
AKA Nullable DateTime。DateTimeConverter数据库“CanConvert”同时包含DateTime和DateTime?谢谢,抱歉!作为对任何被它抓住的人的进一步说明,OP要求从unix MICRO sec获得一个转换器
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);
    }
}
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime lastModified;
Public DateTime TimeToBeShown {get; set;}
Public long DateThatIsComingAsJsonFormat {get; set;}
     var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
     TimeToBeShown=dateTime.AddSeconds(somethingfromloop.CreatedTime).ToLocalTime();
Bind to TimeToBeShown in Xaml