1

I've a method that deserialize string into a type.

var data = JsonConvert.DeserializeObject<TestData>("invalid json");

If string is not valid, JsonReaderException occurring.

I want to return default value of TestData (null) when string is not valid instead of throw exception.

How can I do this without try/catch and JObject?

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41

1 Answers1

4

You can use JsonSerializerSettings to handle it the result of it will be NULL. The reference of JsonConvert.DeserializeObject and JsonSerializerSettings.Error

var settings = new JsonSerializerSettings 
{
    Error = (se, ev) => 
    { 
        ev.ErrorContext.Handled = true; 
    } 
};
var data = JsonConvert.DeserializeObject<Currency>("invalid json", settings);
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
MichaelMao
  • 2,596
  • 2
  • 23
  • 54