Unwrapping JsonDynamicObject
<p>I am trying to figure out a loading issue resulting from the <code>Json.Decode</code> function from <code>System.Web.Helpers</code> when iterating through each of the fields.</p>

<p>In my <a href="https://github.com/storydev/sd2edit" rel="nofollow">open source project</a>, I have an extendable type system that allows Extension developers to create their own custom types that can be reused in their projects or others. To save and load these custom types to the same JSON file as the rest of the scene in this visual editor, I am taking advantage of the <code>System.Reflection.Emit</code> namespace to save and load these custom types.</p>

<p>Because these types are loaded dynamically from an external DLL file, my application does not know what these types are until runtime. So using <code>Json.Decode&lt;&gt;</code> method is simply a no-go.</p>

<p>The save functionality works as expected. However, I am having an issue with the load functionality.</p>

<p>The following code is used to load the JSON file wherever <code>instanceType</code> is defined as a type not recognised internally by the editor:</p>

<pre><code>public static void Open(object instance, dynamic data)
{
    var type = instance.GetType();
    var properties = type.GetProperties();
    var dataFields = ((ObjectHandle)data).Unwrap().GetType().GetFields();

    foreach (var pr in properties)
    {
        foreach (var field in dataFields)
        {
            if (pr.CanWrite &amp;&amp; pr.Name == field.Name)
            {
                var value = field.GetValue(data);

                if (pr.PropertyType == typeof(Color))
                {
                    value = Color.FromArgb(value);
                }

                pr.SetValue(instance, field.GetValue(data));
            }
        }
    }
}
</code></pre>

<p>The line starting <code>var dataFields</code> is where the issue is, and I have researched online as much as possible for a potential solution, but I can't find one related to <code>JsonDynamicObject</code>.</p>

<p>The error is as follows:</p>

<pre><code>An unhandled exception of type 'System.InvalidOperationException' occurred in System.Web.Helpers.dll

Additional information: Unable to convert to "System.Runtime.Remoting.ObjectHandle". Use Json.Decode&lt;T&gt; instead.
</code></pre>

<p>Now, I cannot use <code>Json.Decode&lt;T&gt;</code> for the reasons I just mentioned, so is there any other way I can read the fields of this dynamic object?</p>

<p>I tried changing the second argument type to an object, but this resulted in a casting error:</p>

<pre><code>An unhandled exception of type 'System.InvalidCastException' occurred in sd2api.dll

Additional information: Unable to cast object of type 'System.Web.Helpers.DynamicJsonObject' to type 'System.Runtime.Remoting.ObjectHandle'.
</code></pre>