When I send a request to a service (that I do not own), it may respond either with the JSON data requested, or with an error that looks like this:
{
\"er
To test whether a text is valid JSON regardless of schema, you could also do a check on the number of quotation marks:" in your string response, as shown below :
// Invalid JSON
var responseContent = "asgdg";
// var responseContent = "{ \"ip\" = \"11.161.195.10\" }";
// Valid JSON, uncomment to test these
// var responseContent = "{ \"ip\": \"11.161.195.10\", \"city\": \"York\", \"region\": \"Ontartio\", \"country\": \"IN\", \"loc\": \"-43.7334,79.3329\", \"postal\": \"M1C\", \"org\": \"AS577 Bell Afgh\", \"readme\": \"https://ipinfo.io/missingauth\"}";
// var responseContent = "\"asfasf\"";
// var responseContent = "{}";
int count = 0;
foreach (char c in responseContent)
if (c == '\"') count++; // Escape character needed to display quotation
if (count >= 2 || responseContent == "{}")
{
// Valid Json
try {
JToken parsedJson = JToken.Parse(responseContent);
Console.WriteLine("RESPONSE: Json- " + parsedJson.ToString(Formatting.Indented));
}
catch(Exception ex){
Console.WriteLine("RESPONSE: InvalidJson- " + responseContent);
}
}
else
Console.WriteLine("RESPONSE: InvalidJson- " + responseContent);