Note that there are some explanatory texts on larger screens.

plurals
  1. POJSON.NET deserialize to object with Type parameter
    primarykey
    data
    text
    <p>I have the following problem which I am unable to solve:</p> <p>I have different classes which all implement an interface named <code>IProtocol</code>. The are named, for now, <code>SimpleProtocol</code>, <code>ParallelProtocol</code>. I wanted to persist those object so I used JSON.NET and everything works fine. Except when I am trying to deserialize them it works perfectly when I know the type they are supposed to be, for instance:</p> <pre><code>SimpleProtocol p = JsonConvert.DeserializeObject&lt;SimpleProtocol&gt;(myJsonData); </code></pre> <p>However, I am now in a situation where I want to load the JSON data and get an <code>IProtocol</code> back, but that is, understandably, not allowed by JSON; E.g., something like this does <strong>not</strong> work:</p> <pre><code>IProtocol p1 = JsonConvert.DeserializeObject&lt;IProtocol&gt;(myJsonData); // does not work IProtocol p2 = (IProtocol)JsonConvert.DeserializeObject(myJsonData); // also, does not work </code></pre> <p>So, looking up the <a href="http://james.newtonking.com/projects/json/help/index.html?topic=html/Overload_Newtonsoft_Json_JsonConvert_DeserializeObject.htm">API</a> I found this method signature:</p> <pre><code>public static Object DeserializeObject( string value, Type type ) </code></pre> <p>which looks just like the thing I needed, so trying out by also persisting the type in a string and retrieving it:</p> <pre><code>// test Type protocolType = Type.GetType("MyApp.Protocols.SimpleProtocol"); IProtocol p1 = JsonConvert.DeserializeObject(myJsonData, protocolType); </code></pre> <p>I get an error that it is impossible to cast a <code>Newtonsoft.Json.Linq.JObject</code> to <code>IProtocol</code>. This is weird and I don't know how to solve this.</p> <p>It is impossible to pass the Type object in a generic method, so I am basically stuck here. Is there a method to solve this, preferably without using Reflection? It looks to me that this is a perfectly normal use case.</p> <p>What I can do, but it seems a bit 'dirty' to me, is to create a simple wrapper class which holds an IProtocol instance in it and serialize / deserialize that?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload