Is it possible to check if JSONArray is actually boolean or integer array. I've searched trough internet for hours but I can't find anything. Thanks.
2 Answers
You just need to use instanceof on the first element:
JSONObject o = new JSONObject("{ \"a1\": [ false, true, false, true ], \"a2\": [1,2,3,4] }");
JSONArray a1 = o.getJSONArray("a1");
JSONArray a2 = o.getJSONArray("a2");
if (a1.length() > 0) {
if (a1.get(0) instanceof Boolean) {
System.out.println("a1 is Boolean array");
} else if (a1.get(0) instanceof Integer) {
System.out.println("a1 is Integer array");
} else {
System.out.println("a1 is some other type");
}
}
if (a2.length() > 0) {
if (a2.get(0) instanceof Boolean) {
System.out.println("a2 is Boolean array");
} else if (a2.get(0) instanceof Integer) {
System.out.println("a2 is Integer array");
} else {
System.out.println("a2 is some other type");
}
}
Comments
If you are using JSONArray from org.json package then you can do 2 things.
1) you can use optBoolean or optInt methods which return true if value is boolean or int respectively, as doc says here
2) you can get JSONArray value in Object and check its instance by instanceOf keyword and then use appropriately.