Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if response from server is JSONAobject or JSONArray? [duplicate]

Tags:

json

android

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 ?

like image 260
user691285 Avatar asked Feb 04 '13 11:02

user691285


People also ask

How does JSONArray differ from JSON object?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

Can we convert JSONArray to JSON object?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.


1 Answers

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
    //...
}
like image 156
Rajesh Avatar answered Sep 19 '22 08:09

Rajesh