namrata
namrata

Reputation: 2545

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

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?

Upvotes: 9

Views: 16660

Answers (3)

Harsh Patel
Harsh Patel

Reputation: 1

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

Upvotes: 0

Power Mouse
Power Mouse

Reputation: 1441

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;
        }
    }

}

Upvotes: 1

Kalten
Kalten

Reputation: 4302

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.

Upvotes: 18

Related Questions