gpt4 book ai didi

c# - newtonsoft jobject.Value() 将不起作用

转载 作者:行者123 更新时间:2023-11-30 21:44:40 24 4
gpt4 key购买 nike

当我使用以下代码时:

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。

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

我是否遗漏了一些明显的东西?谢谢。

最佳答案

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

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

对于你的情况,它变成了:

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

所以它明确地使用了InvariantCulture。如果您的文化与此不同 - 您将看到一个异常(exception)。

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

关于c# - newtonsoft jobject.Value<DateTime>() 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40708717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com