问题描述
代码如下:
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 上禁用反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!