LukAss741 LukAss741 - 12 days ago 5
JSON Question

newtonsoft jobject.Value<DateTime>() won't work

When I use following code:

string jsonStr = JsonConvert.SerializeObject(new
{
savedAtGMT0 = DateTime.UtcNow.ToString()
});
MessageBox.Show(jsonStr);
JObject jsonObj = JObject.Parse(jsonStr);
MessageBox.Show(jsonObj["savedAtGMT0"].Value<string>());
MessageBox.Show(DateTime.Parse(jsonObj["savedAtGMT0"].Value<string>()).ToString());
MessageBox.Show(jsonObj["savedAtGMT0"].Value<DateTime>().ToString());


MessageBox.Show(jsonStr);
shows:

{"savedAtGMT0":"20.11.2016 19:39:23"}


MessageBox.Show(jsonObj["savedAtGMT0"].Value<string>());
shows:

20.11.2016 19:39:23


MessageBox.Show(DateTime.Parse(jsonObj["savedAtGMT0"].Value<string>()).ToString());
shows:

20.11.2016 19:39:23


MessageBox.Show(jsonObj["savedAtGMT0"].Value<DateTime>().ToString());
throws an exception:

System.FormatException: String was not recognized as a valid DateTime.


Why is that happening? I don't specify any formatting therefore I believe it should use my system's culture formatting for conversion from DateTime to string and from string to DateTime.

Note that I am fairly certain that the same code used to work in the past.

Am I missing something obvious? Thanks.

Evk Evk
Answer

That's because internally it uses Convert.ChangeType in the following way:

(U) Convert.ChangeType(jvalue.Value, type, (IFormatProvider) CultureInfo.InvariantCulture);

For your case it becomes then:

(DateTime) Convert.ChangeType(DateTime.UtcNow.ToString(), typeof(DateTime), (IFormatProvider)CultureInfo.InvariantCulture);

So it uses InvariantCulture explicitly. If your culture differs from that - you will have an exception like you observe.

Note that storing dates in culture-specific format in json is not very good idea anyway.

Comments