Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to explicitly cast JValue to a target type before using it?

I have some code like this:

var jsonSerializer = new JsonSerializer();
var json = @"{ ""LastModifiedTime"": ""2013-04-19T18:18:09+03:00"" }";
var result = jsonSerializer.Deserialize<dynamic>(new JsonTextReader(new StringReader(json)));

File.SetLastWriteTime("c:/temp/somefile.txt", result.LastModifiedTime);

However, this gives me (at run time since we are speaking about dynamic here):

RuntimeBinderException
The best overloaded method match for 'System.IO.File.SetLastWriteTime(string, System.DateTime)' has some invalid arguments 

This feels a bit silly. To me, a bit of the point of dynamic is to not have to explicitly specify types and so forth; this should (ideally) be handled by the runtime. Of course, it may be a bit hard for JSON.NET to know what it should masquerade as in a given situation...

James (or anyone else familiar with the JSON.NET internals), is this by design? If I add a manual DateTime cast like this:

File.SetLastWriteTime("c:/temp/somefile.txt", (DateTime) result.LastModifiedTime);

...all works fine.

like image 896
Per Lundberg Avatar asked Apr 22 '13 10:04

Per Lundberg


1 Answers

Found the answer here right before posting...

It turns out that I either have to cast, or to use the Value property of JValue. Still, some more details about this would be nice. Of course, just being able to magically use my JValue as parameter to a 3rd party method without having to worrying about casting would be optimal, giving the most "dynamic language"-like experience with this (otherwise really great!) functionality of JSON.NET.

like image 128
Per Lundberg Avatar answered Oct 20 '22 10:10

Per Lundberg