Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading