c# check if json is valid code example
Example 1: how to test if string is a valid json string c#
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;
}
}
Example 2: 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());
}