Json.NET禁用日期时间反序列化 [英] Json.NET Disable the deserialization on DateTime
问题描述
下面是code:
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的类型是日期,o2.ToString()是8/7/2012下午9点54分45秒。
Now, if we check o2, o2's type is Date, o2.ToString() is 8/7/2012 9:54:45 PM.
我的问题是:
是有办法禁用JObject.Parse日期反序列化,和刚刚获得原始字符串?
在此先感谢
推荐答案
当从对象
解析到 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
});
不幸的是解析
没有这个选项,虽然这将是有意义的拥有它。纵观源解析
我们可以看到,它是所有实例化一个 JsonReader
,然后通过该为加载
。 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:
JsonReader reader = new JsonTextReader(new StringReader(j1.ToString()));
reader.DateParseHandling = DateParseHandling.None;
JObject o = JObject.Load(reader);
这篇关于Json.NET禁用日期时间反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!