本文介绍了如何反序列化日期(毫秒)与JSON.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用类似下面的响应:

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

反序列化调用pretty的简单:

The call to deserialize is pretty simple:

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

这导致异常:

无法将字符串转换为日期时间:1278448832702

有没有一种方法可以让我得到JSON.NET正确反序列化这个日期?

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

推荐答案

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

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

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

这篇关于如何反序列化日期(毫秒)与JSON.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:51