使用JsonConvert反序列化单个DateTime对象 [英] Deserialize a single DateTime object with JsonConvert
问题描述
上下文
JsonConvert.SerializeObject(DateTime.Now)
行给出以下结果:
"2018-05-25T07:59:27.2175427 + 02:00"
但是,当我尝试使用以下行将这个JSON字符串反序列化为DateTime时:JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
它给出Newtonsoft.Json.JsonReaderException
并显示以下消息:
解析值时遇到意外字符:2.路径",第1行,位置1.
到目前为止我还尝试了什么
"2018-05-25T07:59:27"
导致完全相同的异常
问题
具有JSON序列化格式的datetime字符串,我想在其中包含一个DateTime
变量和正确的值.我该如何完成这项任务?
如 JSON标准所示,必须用JSON字符串文字加引号:
A
string
是零个或多个Unicode字符的序列,使用反斜杠转义符将其括在双引号中.字符表示为单个字符串.字符串非常类似于C或Java字符串.
因此,要成为有效的JSON,您的c#字符串文字必须包含周围的双引号,如下所示:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
很容易混淆最外层的引号,它们是c#语言的一部分,并在c#代码中分隔字符串,但不包含在字符串本身中,而内部的引号则是字符串文字本身的一部分. /p>
样本小提琴此处.
Context
The line JsonConvert.SerializeObject(DateTime.Now)
gives the following result:
"2018-05-25T07:59:27.2175427+02:00"
However when I try to deserialize this JSON string to a DateTime with the line: JsonConvert.DeserializeObject<DateTime>("2018-05-25T07:59:27.2175427+02:00")
it gives an Newtonsoft.Json.JsonReaderException
with the following message:
Unexpected character encountered while parsing value: 2. Path '', line 1, position 1.
What else I've tried so far
"2018-05-25T07:59:27"
causes the very same exception
Question
Having the datetime string in JSON serialized format, I would like to have a DateTime
variable and the correct value in it. How can I accomplish this task?
As shown in the JSON standard, a JSON string literal must be quoted:
A
string
is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
Thus, to be valid JSON, your c# string literal must include the surrounding double quotes, like so:
var dateTime = JsonConvert.DeserializeObject<DateTime>("\"2018-05-25T07:59:27.2175427+02:00\"");
It's easy to confuse the outermost quotes, which are part of the c# language and delimit the string in your c# code but are not included in the string itself, with the inner quotes, which are part of the string literal itself.
Sample fiddle here.
这篇关于使用JsonConvert反序列化单个DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!