How to deserialize date (milliseconds) with JSON.NET?

六眼飞鱼酱① 提交于 2019-12-18 21:17:44

问题


I'm working with a response like the following:

{"id":"https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P",
"issued_at":"1278448832702","instance_url":"https://na1.salesforce.com",
"signature":"0CmxinZir53Yex7nE0TD+zMpvIWYGb/bdJh6XfOH6EQ=","access_token":
"00Dx0000000BV7z!AR8AQAxo9UfVkh8AlV0Gomt9Czx9LjHnSSpwBMmbRcgKFmxOtvxjTrKW1
9ye6PE3Ds1eQz3z8jr3W7_VbWmEu4Q8TVGSTHxs"}

I'm trying to deserialize this into a class that looks like:

public class TokenResponse {
    public string Id { get; set; }
    [JsonProperty(PropertyName = "issued_at")]
    public DateTime IssuedAt { get; set; }
    public string Signature { get; set; }
    [JsonProperty(PropertyName = "instance_url")]
    public string InstanceUrl { get; set; }
    [JsonProperty(PropertyName = "access_token")]
    public string AccessToken { get; set; }
}

The call to deserialize is pretty simple:

JsonConvert.DeserializeObject<TokenResponse>(response.Content);

This results in an exception:

Could not convert string to DateTime: 1278448832702.

Is there a way I can get JSON.NET to deserialize this date correctly?


回答1:


You can create a custom DateTime converter

var token = JsonConvert.DeserializeObject<TokenResponse>(response.Content, 
                                                      new MyDateTimeConverter());

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



回答2:


I don't think that's milliseconds per se, but instead the Unix epoch time, c.f. this article I found on developerforce.com

I believe that this could help - it describes writing a custom JsonConverter which you can use with JSON.net to convert these epoch times to a DateTime.



来源:https://stackoverflow.com/questions/18088406/how-to-deserialize-date-milliseconds-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!