当前位置: 首页 > 编程语言 > C#

如何使用JSON.NET反序列化日期(毫秒)?Share

时间:2023-04-11 01:47:49 C#

如何使用JSON.NET反序列化日期(毫秒)?我正在处理这样的响应:{"id":"https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P","issued_at":"1278448832702","instance_url":"https://na1.salesforce.com","signature":"0CmxinZir53Yex7nE0TD+zMpvIWYGb/bdJh6XfOH6EQ=","access_token":"00Dx0000000BV7z!AR8AQAxo9UfVkh8AlV0Gomt9Czx9LjHnSSpwBMmbRcgKFmxOtvxjTrKW19ye6PE3Ds1eQz3z8jr3W7_VbWmEu4Q8TVGSTHxs"}我正在尝试将其反序列化为类似于以下内容的类:publicclassTokenResponse{publicstringId}[JsonProperty(PropertyName="issued_at")]publicDateTimeIssuedAt{get;放;}publicstringSignature{get;放;}[JsonProperty(PropertyName="instance_url")]publicstringInstanceUrl{get;放;}[JsonProperty(PropertyName="access_token")]publicstringAccessToken{get;放;反序列化的调用很简单:JsonConvert.DeserializeObject(response.Content);这会导致异常:CouldnotconvertstringtoDateTime:1278448832702。有没有办法让JSON.NET正确反序列化此日期?您可以创建构建自定义DateTime转换器vartoken=JsonConvert.DeserializeObject(response.Content,newMyDateTimeConverter());公共类MyDateTimeConverter:Newtonsoft.Json.JsonConverter{publicoverrideboolCanConvert(TypeobjectType){returnobjectType==typeof(DateTime);}publicoverrideobjectReadJson(JsonReaderreader,TypeobjectType,objectexistingValue,JsonSerializerserializer){vart=long.Parse((string)reader.Value);返回新的DateTime(1970,1,1,0,0,0,DateTimeKind.Utc).AddMilliseconds(t);}publicoverridevoidWriteJson(JsonWriterwriter,objectvalue,JsonSerializerserializer){thrownewNotImplementedException();我不认为这是毫秒本身,而是Unix纪元时间,请参阅我在developerforce.com上找到的这篇文章,我相信它可能会有所帮助-它描述了编写一个自定义JsonConverter,您可以将其与JSON.net一起使用以进行转换这些纪元时间到DateTime以上是C#学习教程:Howtodeserializeadate(milliseconds)usingJSON.NET?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: