How to simplify casting of a JToken based on its JTokenType
<p>Is there any solution to refactor following switch/case code in a nicer/shorter way ?</p>

<ul>
<li><code>property.Value</code> is a <code>JToken</code></li>
<li><code>opportunity</code> is a CRM Dynamics entity (similar to a Dictionary)</li>
</ul>

<p>I've tried with following approach without success (it's not acceptable C#)</p>

<pre><code>Type target = property.Value.Type.GetType();
opportunity[property.Key] = property.Value.Value&lt;target&gt;();
</code></pre>

<hr>

<p>Here is the code I'm trying to simplify. (<code>JTokenType.Object</code> and <code>JTokenType.Array</code> are handled in a different way.)</p>

<pre><code>                switch (property.Value.Type)
                {
                    case JTokenType.Boolean:
                        opportunity[property.Key] = property.Value.Value&lt;bool&gt;();
                        break;
                    case JTokenType.Date:
                        opportunity[property.Key] = property.Value.Value&lt;DateTime&gt;();
                        break;
                    case JTokenType.Integer:
                        opportunity[property.Key] = property.Value.Value&lt;int&gt;();
                        break;
                    case JTokenType.String:
                        opportunity[property.Key] = property.Value.Value&lt;string&gt;();
                        break;
                    case JTokenType.Guid:
                        opportunity[property.Key] = property.Value.Value&lt;Guid&gt;();
                        break;
                }
</code></pre>

<hr>

<p>I also tried this as suggested by @diiN_:</p>

<pre><code>opportunity[property.Key] = property.Value.Value&lt;dynamic&gt;();
</code></pre>

<p>but it throws an InvalidDataContractException:
<a href="https://i.stack.imgur.com/5M0Zh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5M0Zh.png" alt="visual studio exception"></a></p>