Json.NET Disable the deserialization on DateTime(Json.NET 在 DateTime 上禁用反序列化)
问题描述
代码如下:
string s = "2012-08-08T01:54:45.3042880+00:00";
JObject j1 = JObject.FromObject(new
{
time=s
});
Object o = j1["time"];
我们可以检查 o 是字符串并且等于2012-08-08T01:54:45.3042880+00:00"
We can check that o is string and equals "2012-08-08T01:54:45.3042880+00:00"
现在我们将 j1.ToString() 转移到另一个程序,即
Now we transfer j1.ToString() to another program, which is
{
"time": "2012-08-08T01:54:45.3042880+00:00"
}
然后在另一个程序中,尝试将其解析回JObject,即
then at the other program, try to parse it back to JObject, which is
JObject j2 = JObject.Parse(j1.ToString());
Object o2 = j2["time"];
现在,如果我们检查 o2,o2 的类型是 Date,o2.ToString() 是 8/7/2012 9:54:45 PM.
Now, if we check o2, o2's type is Date, o2.ToString() is 8/7/2012 9:54:45 PM.
我的问题是:
有没有办法禁用 JObject.Parse 的日期反序列化,只获取原始字符串?
提前致谢
推荐答案
从 object 解析为 JObject 时,可以指定 JsonSerializer它指示如何处理日期.
When parsing from an object to JObject you can specify a JsonSerializer which instructs how to handle dates.
JObject.FromObject(new { time = s },
new JsonSerializer {
DateParseHandling = DateParseHandling.None
});
不幸的是,Parse 没有这个选项,尽管拥有它是有意义的.查看 Parse 的源代码,我们可以看到它所做的只是实例化一个 JsonReader,然后将其传递给 Load.JsonReader 确实有解析选项.
Unfortunately Parse doesn't have this option, although it would make sense to have it. Looking at the source for Parse we can see that all it does is instantiate a JsonReader and then passes that to Load. JsonReader does have parsing options.
你可以像这样达到你想要的结果:
You can achieve your desired result like this:
using(JsonReader reader = new JsonTextReader(new StringReader(j1.ToString()))) {
reader.DateParseHandling = DateParseHandling.None;
JObject o = JObject.Load(reader);
}
这篇关于Json.NET 在 DateTime 上禁用反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.NET 在 DateTime 上禁用反序列化
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
