JObject.ToObject<T>() extension method transforms datetime values stored as strings

c#, datetime, json.net

Solution

what you want is

using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        var temp = JsonConvert.DeserializeObject<A>("{\"aprop\":\"2012-12-02T23:03:31Z\"}");
        Console.ReadKey();
    }
}

as soon as you do `Parse` since "2012-12-02T23:03:31Z\" is a date the parser creates a Date Object everything after that will already have the object parsed so the `.ToObject` is useless as what you are doing is going from date to string and that's why you get the "12/...".

Problem

When calling ToObject on JObject with a string property, transforms datetime value. ``` class Program { static void Main(string[] args) { var a = JObject.Parse("{\"aprop\":\"2012-12-02T23:03:31Z\"}"); var jobject = a.ToObject<A>(); Console.ReadKey(); } } public class A { public string AProp { get; set; } } ``` The problem is I get my value transformed despite it being a string. The ISO8601 specific characters got skipped: I expect no tranformations to happen and want to be able to do date validation and culture-specific creation myself. I also tried the next code without success: ``` var jobject = a.ToObject<A>(new JsonSerializer { DateParseHandling = DateParseHandling.None }); ``` The JObject.Parse is introduced for example's sake. In my real task I have a Web.Api action on a controller: ``` public HttpResponseMessage Put(JObject[] requestData) { var jobject = a.ToObject<A>(); return SomeCleverStaffResponse(); } ```

Original source