title: Using Json.net to deserialize to any unkown type works for objects but not value types
body: <p>I've implemented a Json Serializer based on Json.net to accept any object type and serialize it (for placement into my cache)</p>
  
  <p>The cache interface doesn't allow me to speficy the type, so When I retrieve from the cache I need to dynamically create the type from the meta information.</p>
  
  <p>Which works well for objects, the problem I am now facing is that i doesn't work for value types, I will get an exception saying something along the lines of <code>cannot cast JValue to JObject</code>.</p>
  
  <p>My question is how can I cater for value types as well as object types? It would be great if there was a TryParse for a JObject, which I could write myself, but feel like I am going down a rabbit hole?</p>
  
  <p>What is the best way to achieve this?</p>
  
  <p>My code is as follows, settings for Json.net:</p>
  
  <pre><code>_settings = new JsonSerializerSettings
              {
                  ContractResolver = new CamelCasePropertyNamesContractResolver(),
                  NullValueHandling = NullValueHandling.Ignore,
                  DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                  TypeNameHandling = TypeNameHandling.All
              };
  
  _settings.Converters.Add(new StringEnumConverter());
  </code></pre>
  
  <p>The set function (serialize):</p>
  
  <pre><code>public void Put(string cacheKey, object toBeCached, TimeSpan cacheDuration)
          {
              _cache.Set(cacheKey, JsonConvert.SerializeObject(toBeCached, _settings), cacheDuration);
          }
  </code></pre>
  
  <p>And the get (deserialize):</p>
  
  <pre><code> public object Get(string cacheKey)
      {
          try
          {
              var value = _cache.Get(cacheKey);
  
              if (!value.HasValue)
              {
                  return null;
              }
  
              var jobject = JsonConvert.DeserializeObject&lt;JObject&gt;(value);
              var typeName = jobject?["$type"].ToString();
  
              if (typeName == null)
              {
                  return null;
              }
  
              var type = Type.GetType(typeName);
              return jobject.ToObject(type);
          }
          catch (Exception e)
          {
              // Todo
              return null;
          }
      }
  </code></pre>