Deserialize json in a “TryParse” way

@Victor LG’s answer using Newtonsoft is close, but it doesn’t technically avoid the a catch as the original poster requested. It just moves it elsewhere. Also, though it creates a settings instance to enable catching missing members, those settings aren’t passed to the DeserializeObject call so they are actually ignored.

Here’s a “catch free” version of his extension method that also includes the missing members flag. The key to avoiding the catch is setting the Error property of the settings object to a lambda which then sets a flag to indicate failure and clears the error so it doesn’t cause an exception.

 public static bool TryParseJson<T>(this string @this, out T result)
 {
    bool success = true;
    var settings = new JsonSerializerSettings
    {
        Error = (sender, args) => { success = false; args.ErrorContext.Handled = true; },
        MissingMemberHandling = MissingMemberHandling.Error
    };
    result = JsonConvert.DeserializeObject<T>(@this, settings);
    return success;
}

Here’s an example to use it:

if(value.TryParseJson(out MyType result))
{ 
    // Do something with result…
}

Leave a Comment