Json.NET 在 DateTime 上禁用反序列化

Json.NET Disable the deserialization on DateTime(Json.NET 在 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 上禁用反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)