Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a response string is a JSON Object or an XML?

Tags:

json

c#

json.net

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?

like image 294
namrata Avatar asked Feb 01 '17 22:02

namrata


1 Answers

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.

like image 171
Kalten Avatar answered Sep 26 '22 17:09

Kalten