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 ?
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.
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.
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
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With