8

C# code to check if a response string is a JSON Object or an XML?

I am trying this :

string responseString = jQuery.parseJSON(response.Content.ReadAsStringAsync().Result);

But this will throw an exception if the result is not a valid JSON object. ( This is returning XML content for me, in some cases) I want to avoid exception handling. Is there any method which returns bool to check if this is valid json or not?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
namrata
  • 2,235
  • 5
  • 28
  • 35

3 Answers3

17

Check the content type of the response message.

if (response.Content.Headers.ContentType.MediaType == "application/json")
{
    // parse json
}
else
{
    // parse xml
}

You can also read the first character from the response. If it's a XML content, you should find a <. Even if the XML declaration is present or not.

Kalten
  • 4,092
  • 23
  • 32
0

on string level:


using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
public static class Extentions
{

    public static bool IsValidJson(this string value)
    {
        try
        {
            var json = JContainer.Parse(value);
            return true;
        }
        catch
        {
            return false;
        }
    }

}
Power Mouse
  • 727
  • 6
  • 16
0

Swift code to check if a response string is a JSON or XML

if response.mimeType == "application/xml" {
   //XML
} else if response.mimeType == "application/json" {
   //JSON
} else {
   //Other
}

https://developer.apple.com/documentation/foundation/urlresponse/1411613-mimetype