How to check if the response from the server is JSONAobject or JSONArray?

Possible duplicate:
Determine if JSON is JSONObject or JSONArray

I have a server that returns JSONArray by default, but when some kind of error occurs, it returns me a JSONObject with an error code. I am trying to parse json and check for errors, I have a piece of code that checks for errors:

public static boolean checkForError(String jsonResponse) { boolean status = false; try { JSONObject json = new JSONObject(jsonResponse); if (json instanceof JSONObject) { if(json.has("code")){ int code = json.optInt("code"); if(code==99){ status = true; } } } } catch (Exception e) { e.printStackTrace(); } return status ; } 

but I get a JSONException when jsonResponse is ok and JSONArray (JSONArray cannot be converted to a JSONOBject). How to check if jsonResponse will provide JSONArray or JSONObject?

+7
source share
2 answers

Use JSONTokener . JSONTokener.nextValue() will give you an Object that can be dynamically added to the appropriate type depending on the instance.

 Object json = new JSONTokener(jsonResponse).nextValue(); if(json instanceof JSONObject){ JSONObject jsonObject = (JSONObject)json; //further actions on jsonObjects //... }else if (json instanceof JSONArray){ JSONArray jsonArray = (JSONArray)json; //further actions on jsonArray //... } 
+15
source

You are trying to convert the String response received from the server to a JSONObject that throws an exception. As you said, you will get JSONArray from the server, you will try to convert it to JSONArray . See the JSONObject help you convert the response of a JSONObject and JSONArray . If your answer starts with [(Open Square Bracket), then convert it to JsonArray, as shown below

 JSONArray ja = new JSONArray(jsonResponse); 

if your answer starts with {(open flower Bracket), then convert it to

 JSONObject jo = new JSONObject(jsonResponse); 
0
source

All Articles