JamesNK/Newtonsoft.Json — pull request #372 by ashmind (2014-09-10 02:40:51+00:00)
Title: Added support for JObject dynamic casts

This pull requests adds support for casting dynamic JObject to any type (that ToObject works for).

Basically: `(T)(dynamic)jobject` is `jobject.ToObject()`.

Use case is something like this:

public void Post(Container container) { ... }

public class Container {
public dynamic Content { get; set; }
// some properties that define what content actually is
}

// ...
X x = (X)container.Content; // no references to Newtonsoft.Json in this code

Another similar case I had was with `IDictionary` where value might need to be cast depending on the situation.

Comments on the modifications:

1. My main goal was to limit the changes, both because of limited time I have right now, and to avoid breakage/unexpected architectural decisions. If you think there is more to be done here (as per following items), it is fine -- I'll do it when I get more time.

2. I haven't passed the original serializer through to `ToObject`, since the proxy does not currently have access to that, so it would need more changes. However I think it is something that must be done sooner or later. Should I do that before this is merged?

3. I've added test on the positive case only, not sure if any exception testing is required.

4. The cast seems useful on `JToken` level, especially since `ToObject` is on `JToken` anyway (and I do not see why I wouldn't want to cast dynamic `JArray` to something like `X[]`). However there is no common base type for `JToken` `DynamicProxy`, and `JValue` implementation seems to use some custom logic for `TryConvert`.