7

Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray

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

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 JSONException when jsonResponse is ok and it's a JSONArray (JSONArray cannot be converted to JSONOBject)How to check if jsonResponse will provide me with JSONArray or JSONObject ?

Community
  • 1
  • 1
user691285
  • 401
  • 1
  • 6
  • 17

2 Answers2

16

Use JSONTokener. The JSONTokener.nextValue() will give you an Object that can be dynamically cast 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
    //...
}
Rajesh
  • 15,724
  • 7
  • 46
  • 95
0

You are trying the convert String response you get from Server into JSONObject which is causing the Exception. As you said you will get the JSONArray from Server, you try to convert into JSONArray. Please refer this link which will help you when to convert string response to JSONObject and JSONArray. If you response starts with [ (Open Square Bracket) then convert it to JsonArray as below

JSONArray ja = new JSONArray(jsonResponse);

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

JSONObject jo = new JSONObject(jsonResponse);
Community
  • 1
  • 1
TNR
  • 5,839
  • 3
  • 33
  • 62