How to tell if Body in HttpWebResponse is Json or XML

I am writing a a class in VB.Net which makes calls for RestAPI's via HttpWebRequest. All works fine and i get the response i am expecting.
What i am looking for is some simple method to evaluate the Body if it is a Json Object, Json Array or an XML doc so i know how to handle
the return data. I don't have any schema to validate against. I just want to know what type of data it is.
Confused CoderAsked:
Who is Participating?
 
Confused CoderAuthor Commented:
i patched together a basic function which does it for me now, it take the doc checks if it is a Json if we throw exception we check for xml and if we fail return invalid.

Private Function validate_doc(ByVal myBody As String) As String
        Dim DocType As String = ""
        Try
            DocType = JToken.Parse(myBody).Type.ToString
        Catch ex As Exception
            Try
                Dim xmlTest As String = XElement.Parse(myBody).FirstNode.ToString
                DocType = "XML"
            Catch ex2 As Exception
                DocType = "Ivalid"
            End Try
        End Try
        Return DocType
    End Function

Open in new window

0
 
zc2Commented:
The HttpWebResponse object has a property called ContentType, you can analyze its content to guess the type of the request without looking the response body itself.
 ContentType content could be "text/xml" or "application/json" or similar, enough to make that decision.
0
 
Confused CoderAuthor Commented:
That would be great in an ideal world but its not 100% as I have for example an external API i am calling who returns
Content-Type: text/html; charset=UTF-8 even so the body is a Json doc. Also even should i go the route i still would not
know if its a single doc or an array of docs in my body.
0
 
zc2Commented:
Think, you are right, and analyzing the response content body is the only way to handle your problem.
BTW, instead of parsing the whole content, you just can try to search for some format specific signatures, like  "/>" for XML and "{" for json.
Also, parse is a quite heavy operation. Now you parse the content twice. First for detection in the validate_doc() function, then you throw the result away and then you need to parse again to extract data. If you still prefer parsing, I'd recommend to try to combine that to a one routine. Parse as JSON, if no exception, use it for further processing, same way the XML.
0
 
Confused CoderAuthor Commented:
Content type is not reliable to determine what is in body of response as well it does not tell me if its a Json Object or Array
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.