If it's a JsonArray object, just use getAsJsonArray() to cast it. If not, it's a single element so just add it.
JSONArray interventions; if(intervention == null) interventions=jsonObject. optJSONArray("intervention"); This will return you an array if it's a valid JSONArray or else it will give null .
To check if JavaScript object is JSON, we can use the JSON. parse method. const isJson = (data) => { try { const testIfJson = JSON. parse(data); if (typeof testIfJson === "object") { return true; } else { return false; } } catch { return false; } };
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.
I found better way to determine:
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()
There are a couple ways you can do this:
{
, you are dealing with a JSONObject
, if it is a [
, you are dealing with a JSONArray
.Object
), then you can do an instanceof
check. yourObject instanceof JSONObject
. This will return true if yourObject is a JSONObject. The same applies to JSONArray.This is the simple solution I'm using on Android:
JSONObject json = new JSONObject(jsonString);
if (json.has("data")) {
JSONObject dataObject = json.optJSONObject("data");
if (dataObject != null) {
//Do things with object.
} else {
JSONArray array = json.optJSONArray("data");
//Do things with array
}
} else {
// Do nothing or throw exception if "data" is a mandatory field
}
Presenting an another way :
if(server_response.trim().charAt(0) == '[') {
Log.e("Response is : " , "JSONArray");
} else if(server_response.trim().charAt(0) == '{') {
Log.e("Response is : " , "JSONObject");
}
Here server_response
is a response String coming from server
A more fundamental way of doing this is the following.
JsonArray
is inherently a List
JsonObject
is inherently a Map
if (object instanceof Map){
JSONObject jsonObject = new JSONObject();
jsonObject.putAll((Map)object);
...
...
}
else if (object instanceof List){
JSONArray jsonArray = new JSONArray();
jsonArray.addAll((List)object);
...
...
}
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