Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Check Response is JSON or not

Tags:

java

json

I am creating a Server HealthCheck page. Most of the servers return JSONObject and I am able to easily parse it using:

String jsonText = readAll(br);              
JSONObject json = new JSONObject(jsonText);
JSONObject resp = json.getJSONObject("Response");

Now my problem is the other servers that do not return JSON. Some are returning String, some pdf file some image and as all the responses are 200 OK I should return Positive healthcheck.

However I am using Future Threads and timing out my request after 4 secs. And all the servers which return anything other than JSON get stuck at " new JSONObject(jsonText);"

Is there any way I can check if the type of respone is JSON or not in Java?

Update:

I found my mistake - stupid one. In the try catch block I am only catching IOException, which is not catching JSONException(and didnt show any error too - dunno y). I have added a new catch block for JSONException which works for my solution for now.

However, this isnt elegant solution, @Dave, @Radai and @Koi 's solutions is the right approach to go with.

like image 790
Rahul Dabas Avatar asked Feb 16 '23 11:02

Rahul Dabas


2 Answers

Don't parse the string. Go back one step, and check the Content-Type header of the HTTP response. If the response contains JSON data, the Content-Type should be application/json (source).

like image 103
kol Avatar answered Feb 20 '23 09:02

kol


Check the MediaType in the response using response.getMediaType(). If it is json it returns application/json.

like image 37
Raju Bairishetti Avatar answered Feb 20 '23 09:02

Raju Bairishetti