0

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 2

1

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");
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.