Json.NET Disable the deserialization on DateTime

C#Datetimejson.netDeserialization

C# Problem Overview


Here is the code:

        string s = "2012-08-08T01:54:45.3042880+00:00";

        JObject j1 = JObject.FromObject(new
        {
            time=s
        });

        Object o = j1["time"];

We can check that o is string and equals "2012-08-08T01:54:45.3042880+00:00"

Now we transfer j1.ToString() to another program, which is

       {
          "time": "2012-08-08T01:54:45.3042880+00:00"
       }

then at the other program, try to parse it back to JObject, which is

       JObject j2 = JObject.Parse(j1.ToString());

       Object o2 = j2["time"];

Now, if we check o2, o2's type is Date, o2.ToString() is 8/7/2012 9:54:45 PM.

My question is:

Is there is way to disable the Date deserialization for JObject.Parse , and just get the raw string?

Thanks in advance

C# Solutions


Solution 1 - C#

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
                   });

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);
  }

Solution 2 - C#

You can accomplish this using JsonConvert.DeserializeObject as well, by using JsonSerializerSettings:

string s = "2012-08-08T01:54:45.3042880+00:00";
string jsonStr = $@"{{""time"":""{s}""}}";

JObject j1 = JsonConvert.DeserializeObject<JObject>(jsonStr, new JsonSerializerSettings {DateParseHandling = DateParseHandling.None});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionliuhongboView Question on Stackoverflow
Solution 1 - C#Samuel NeffView Answer on Stackoverflow
Solution 2 - C#BobbyAView Answer on Stackoverflow