Last active
March 29, 2022 21:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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