How to check whether an element is a JSONArray or JSONObject. I wrote the code to check,
if(jsonObject.getJSONObject("Category").getClass().isArray()) {
} else {
}
In this case if the element 'category' is JSONObject then it work fine but if it contains an array then it throw exception: JSONArray cannot be converted to JSONObject. Please help. Thanks.
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; } };
Yes, this is because the getJSONObject("category")
will try to convert that String
to a JSONObject what which will throw a JSONException
. You should do the following:
Check if that object is a JSONObject
by using:
JSONObject category=jsonObject.optJSONObject("Category");
which will return a JSONObject
or null
if the category
object is not a json object.
Then you do the following:
JSONArray categories;
if(category == null)
categories=jsonObject.optJSONArray("Category");
which will return your JSONArray
or null if it is not a valid JSONArray
.
Even though you have got your answer, but still it can help other users...
if (Law.get("LawSet") instanceof JSONObject)
{
JSONObject Lawset = Law.getJSONObject("LawSet");
}
else if (Law.get("LawSet") instanceof JSONArray)
{
JSONArray Lawset = Law.getJSONArray("LawSet");
}
Here Law
is other JSONObject
and LawSet
is the key which you want to find as JSONObject or JSONArray
.
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()
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