Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

c# - Deserialize a single DateTime object with JsonConvert

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...