newtonsoft jobject.Value <datetime>()不会工作

时间:2016-11-20 19:57:34

标签: c# json parsing datetime json.net

当我使用以下代码时:

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);显示:

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

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

20.11.2016 19:39:23

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

20.11.2016 19:39:23

MessageBox.Show(jsonObj["savedAtGMT0"].Value<DateTime>().ToString());抛出异常:

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

为什么会这样?我没有指定任何格式,因此我认为它应该使用我的系统的文化格式来从DateTime转换为字符串,从字符串转换为DateTime。

请注意,我相当确定过去曾使用相同的代码。

我错过了一些明显的东西吗?感谢。

1 个答案:

答案 0 :(得分:3)

那是因为在内部它以下列方式使用Convert.ChangeType:

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

对于你的情况,那就是:

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

因此它明确使用InvariantCulture。如果您的文化与此不同 - 您会遇到例外情况。

请注意,无论如何,在json中以特定于文化的格式存储日期并不是一个好主意。