Java Json Convert jsonArrayToBooleanList(final JsonArray arr)

Here you can find the source of jsonArrayToBooleanList(final JsonArray arr)

Description

Convert a json array to a list of booleans.

License

Open Source License

Parameter

Parameter Description
arr array

Exception

Parameter Description
ClassCastException if any element in arr is not an boolean

Return

a list

Declaration

public static List<Boolean> jsonArrayToBooleanList(final JsonArray arr) 

Method Source Code

//package com.java2s;
/**/*from  w  w w.  j  a v a2 s  .  c  o m*/
 * This file is part of the Aerodrome package, and is subject to the 
 * terms and conditions defined in file 'LICENSE', which is part 
 * of this source code package.
 *
 * Copyright (c) 2016 All Rights Reserved, John T. Quinn III,
 * <johnquinn3@gmail.com>
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 */

import java.util.ArrayList;
import java.util.List;

import javax.json.JsonArray;

public class Main {
    /**
     * Convert a json array to a list of booleans.
     * if arr is null, then an empty List<Boolean> instance is returned.
     * 
     * This is more safe than JsonArray.getValuesAs() as this method
     * has built-in type checking and will throw a ClassCastException if 
     * the type is incorrect or null.
     * 
     * @param arr array
     * @return a list
     * @throws ClassCastException if any element in arr is not an boolean
     */
    public static List<Boolean> jsonArrayToBooleanList(final JsonArray arr) {
        final List<Boolean> out = new ArrayList<>();
        if (arr == null)
            return out;

        for (int i = 0; i < arr.size(); i++) {
            final Boolean b = arr.getBoolean(i);
            if (b == null) {
                throw new ClassCastException(
                        "Element at position " + String.valueOf(i) + " is null - Boolean required");
            }

            out.add(b);

            out.add(arr.getBoolean(i));
        }

        return out;
    }
}

Related

  1. jsonArrayToString(final JsonArray array)
  2. toIntArray(JsonArray jsonArray)
  3. toJsonString(JsonObject json)
  4. toList(JsonArray array)