Reputation: 35873
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?
Upvotes: 1
Views: 1335
Reputation: 116785
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.
Upvotes: 3
Reputation: 1500665
The problem is that JsonConvert.DeserializeObject
looks like it wants a JSON object rather than just any JSON value. (It's a shame that SerializeObject
doesn't always produce an object, but...)
You can parse it like this:
DateTime dt = new JValue("2018-05-25T07:59:27.2175427+02:00").ToObject<DateTime>();
Or (equivalently? I'm not entirely sure):
DateTime dt = (DateTime) new JValue("2018-05-25T07:59:27.2175427+02:00");
There may be a better way of doing so, but that at least works.
Upvotes: 3