3

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:

enter image description here

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();
}
Yurii Hohan
  • 4,021
  • 4
  • 40
  • 54

2 Answers2

4

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/...".

Pedro.The.Kid
  • 1,968
  • 1
  • 14
  • 18
0

Why do you parse it, when you don't want to have it parsed, at the first place? There's no reason for building a JObject instance. Just deserialize the string using the JsonSerializer.Deserialize<T> method directly into an A instance. You can then leverage all Json.NET's attributes (among other means) to control deserialization as you want.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
  • I parse it for example's sake, I get JObject as parameted in Web Api action. What I can't get my head around is why should I use Deserialize or DeserializeObject method and cannot tweak the .ToObject() method? – Yurii Hohan Feb 04 '14 at 14:33
  • 1
    Why do you want to *tweak* something if there's a *straightforward* way? Maybe you are not telling the whole context. – Ondrej Tucny Feb 04 '14 at 14:45
  • I have not found a ***straightforward*** way to do it using .ToObject(), you may notice that the symbols specific to ISO8601 were skipped. – Yurii Hohan Feb 04 '14 at 14:52
  • @Yurii what does your Web API method signature look like? – Brian Rogers Feb 04 '14 at 16:42