I'm currently using this method to test a string if it valid JSON. The JToken class depends on Newtonsoft.Json.Linq.
public static bool IsValidJson(this string stringValue)
{
bool returnValue = false;
string value = null;
if (!String.IsNullOrEmpty(stringValue))
value = stringValue.Trim();
if (!String.IsNullOrWhiteSpace(value) &&
((value.StartsWith("{") && value.EndsWith("}")) || //For object
(value.StartsWith("[") && value.EndsWith("]")))) //For array
{
try
{
value = stringValue.Trim();
var obj = JToken.Parse(value);
returnValue = true;
}
catch
{
returnValue = false;
}
}
else
{
returnValue = false;
}
return returnValue;
}
Any recommendations to improve?