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