title: Get JSON.Net to throw Exception if object not of expected type in Generic method
body: <p>I created a generic deserialization method that I pass a json string into.  T is the type that I want returned.  </p>
  
  <pre><code>    private static T Deserialize&lt;T&gt;(string input)
      {
          try
          {
              var result = JsonConvert.DeserializeObject&lt;T&gt;(input);
              return result;
          }
          catch (JsonSerializationException ex)
          {
              var errorResult = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, string&gt;&gt;(input);
  
              var errorMessage = errorResult["error"];
  
              throw new ApplicationException(errorMessage, ex);
          }
      }
  </code></pre>
  
  <p>So to call the method we choose </p>
  
  <pre><code>Deserialize&lt;MyObject&gt;(jsonString)
  </code></pre>
  
  <p>Which successfully returns an object of Type <code>MyObject</code>.</p>
  
  <p>However, the json passed in can sometimes contain an error message (error : message) if things have gone wrong. </p>
  
  <p>What I wanted to do in this case is cause a JsonSerializationException and read the error message. </p>
  
  <p>However, no such error is thrown and the MyObject is retured but with all null and zero values.</p>
  
  <p>Error json</p>
  
  <pre><code>"{\"error\":\"Error message"}"
  </code></pre>
  
  <p>Other json</p>
  
  <pre><code>"[{\"path\":\"\",\"id\":2000,\"name\":\"Name1\"},{\"path\":\"\",\"id\":2001,\"name\":\"Name2\"},{\"path\":\"\",\"id\":2002,\"name\":\"Name3\"}]"
  </code></pre>
  
  <p>The other json could be in pretty much any format - but the point is that the required Type is passed into the method and that is what should get returned or an exception should be thrown.</p>