How to prevent JsonReaderException when json is not valid in JsonConvert.DeserializeObject


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?

>Solution :

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);

Leave a Reply Cancel reply