Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Last active March 29, 2022 21:38
Show Gist options
  • Save csharpforevermore/8bf077fc446c740011ff3cf3fa19a9f5 to your computer and use it in GitHub Desktop.
Save csharpforevermore/8bf077fc446c740011ff3cf3fa19a9f5 to your computer and use it in GitHub Desktop.
Newtonsoft.Json's JsonConvert TryParse extension method - as per Stack Overflow article https://stackoverflow.com/questions/23906220/deserialize-json-in-a-tryparse-way
using Newtonsoft.Json;
public static class JsonConvertHelper
{
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;
}
}
if(value.TryParseJson(out MyType result))
{
// Do something with result…
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment