validating json against a class in c# code example
Example: c# is json valid
private static bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) ||
(strInput.StartsWith("[") && strInput.EndsWith("]")))
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}
string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
Console.WriteLine(fex);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}