0

I have done a lot of searching but not come up with anything which can explain my problem, which I have no doubt is trivial.

I've imported Json.NET 12.0.1 into my project from NuGet.

In the code below, the line

Console.WriteLine(json.Value<DateTimeOffset>("DateTime"));

throws an

Invalid cast from 'System.DateTime' to 'System.DateTimeOffset'

exception, as commented.

So, why can I explicitly cast

json["DateTime"] or json.Value<DateTime>("DateTime") to DateTimeOffset

but not use json.Value<DateTimeOffset>("DateTime")?

using Newtonsoft.Json.Linq;
using System;

namespace JSONDates
{
    class Program
    {
        static void Main(string[] args)
        {
            string dt = "2019-04-21T18:27:21.225+01:00";
            string jsonString = string.Format("{{\"DateTime\": \"{0}\"}}", dt);
            JObject json = JObject.Parse(jsonString);

            Console.WriteLine(json.Value<DateTime>("DateTime")); //OK
            Console.WriteLine((DateTimeOffset)json.Value<DateTime>("DateTime")); //OK
            Console.WriteLine(((DateTimeOffset)json["DateTime"])); //OK
            Console.WriteLine(json.Value<DateTimeOffset>("DateTime")); //{"Invalid cast from 'System.DateTime' to 'System.DateTimeOffset'."}
            Console.ReadLine();

        }
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
spodger
  • 1,668
  • 1
  • 12
  • 16
  • As JSON has no standard way for serializing date/time values, they need a little [configuring](https://www.newtonsoft.com/json/help/html/datesinjson.htm). Specifically, use `DateParseHandling.DateTimeOffset`. – Jeroen Mostert Apr 18 '19 at 10:57
  • @JeroenMostert, I could but the two explicit casts work fine. I just don't understand when the MSDN states there is an `...implicit conversion operator, which allows you to assign a DateTime value to a DateTimeOffset object.` why I get an exception that seems to state the opposite. – spodger Apr 18 '19 at 11:01
  • @JeroenMostert, is the issue that my explicit casts are being done in C# (or the .NET framework) whereas `` is getting Json.NET to do the conversion? – spodger Apr 18 '19 at 11:03
  • That would be my guess, yes. I haven't actually checked the source to see how `JObject.Value` is implemented. There is actually (to my knowledge) no *direct* implementation in the framework of the C# rules for casts and conversions -- notably, things like `Convert.ChangeType` actually play by their own, slightly different set of rules. So usually, whenever you see a runtime conversion somewhere (JSON.NET or otherwise) there's going to be some edge cases where it behaves differently. In this case, that's a *good* thing -- an internal cast would have discarded the time zone info. – Jeroen Mostert Apr 18 '19 at 11:05
  • @JeroenMostert, fair enough and thanks for that. I'll just have to use an explicit cast. I just thought it looked a little ugly and felt it should be unnecessary. But since it doesn't work I'll just have to put up with it. – spodger Apr 18 '19 at 11:09
  • Note that, even with an explicit cast, what you get first is a `DateTime`, which has no time zone info. If you want to round-trip that information, using `DateTime` would not be the way to go -- conversely, if you're fine with losing the information and converting the date to local time, you wouldn't need `DateTimeOffset`. So either way you probably want to change something here. – Jeroen Mostert Apr 18 '19 at 11:10
  • @JeroenMostert, yes I'm just in the discovery mode on this since I am getting sent varying time formats. My test code has about 20 examples examining `DateTime.Kind` and using `DateTime.ToUniversalTime()` and `DateTimeOffset.UtcDateTime` etc. so that I can judge the results and tell the people sending the messages what format to use. My code doesn't need to be time zone aware, just daylight saving aware. – spodger Apr 18 '19 at 11:20
  • Here's an example of how to use [`DateParseHandling.DateTimeOffset`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateParseHandling.htm) when parsing to `JObject`: [How to preserve timezone when deserializing DateTime using JSON.NET?](https://stackoverflow.com/a/27043566/3744182). – dbc Apr 18 '19 at 17:35

0 Answers0