13

我正在处理如下响应:

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

我正在尝试将其反序列化为一个如下所示的类:

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

反序列化的调用非常简单:

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

这会导致异常:

Could not convert string to DateTime: 1278448832702.

有没有办法让 JSON.NET 正确反序列化这个日期?

4

2 回答 2

26

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

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();
    }
}
于 2013-08-06T20:10:59.670 回答
3

我不认为那是毫秒本身,而是 Unix 纪元时间,参见我在 developerforce.com 上找到的这篇文章

我相信会有所帮助 - 它描述了编写一个自定义的 JsonConverter,您可以使用它与 JSON.net 一起将这些纪元时间转换为 DateTime。

于 2013-08-06T19:22:32.137 回答