| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.util.json; |
| 7 |
|
| 8 |
import java.lang.reflect.Array; |
| 9 |
import java.util.ArrayList; |
| 10 |
import java.util.function.Function; |
| 11 |
|
| 12 |
/** |
| 13 |
* JSON array. |
| 14 |
*/ |
| 15 |
public final class JSONArray extends JSONValue { |
| 16 |
|
| 17 |
private final ArrayList<JSONValue> elements = new ArrayList<>(); |
| 18 |
|
| 19 |
JSONArray() { |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Add a value to the array. |
| 24 |
* |
| 25 |
* @param value |
| 26 |
* the value to add |
| 27 |
*/ |
| 28 |
void addElement(JSONValue value) { |
| 29 |
elements.add(value); |
| 30 |
} |
| 31 |
|
| 32 |
@Override |
| 33 |
public void addTo(JSONTarget<?> target) { |
| 34 |
target.startArray(); |
| 35 |
for (JSONValue element : elements) { |
| 36 |
element.addTo(target); |
| 37 |
} |
| 38 |
target.endArray(); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Returns the array length |
| 43 |
* |
| 44 |
* @return the array length |
| 45 |
*/ |
| 46 |
public int length() { |
| 47 |
return elements.size(); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Returns the value. |
| 52 |
* |
| 53 |
* @return the value |
| 54 |
*/ |
| 55 |
public JSONValue[] getArray() { |
| 56 |
return elements.toArray(new JSONValue[0]); |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Returns the value. |
| 61 |
* |
| 62 |
* @param elementType |
| 63 |
* the type of array elements |
| 64 |
* @param converter |
| 65 |
* a converter to the specified type |
| 66 |
* @param <E> |
| 67 |
* type of elements |
| 68 |
* @return the value |
| 69 |
*/ |
| 70 |
public <E> E[] getArray(Class<E> elementType, Function<JSONValue, E> converter) { |
| 71 |
int length = elements.size(); |
| 72 |
@SuppressWarnings("unchecked") |
| 73 |
E[] array = (E[]) Array.newInstance(elementType, length); |
| 74 |
for (int i = 0; i < length; i++) { |
| 75 |
array[i] = converter.apply(elements.get(i)); |
| 76 |
} |
| 77 |
return array; |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Returns the value at specified 0-based index, or {@code null}. |
| 82 |
* |
| 83 |
* @param index |
| 84 |
* 0-based index |
| 85 |
* @return the value at specified 0-based index, or {@code null}. |
| 86 |
*/ |
| 87 |
public JSONValue getElement(int index) { |
| 88 |
if (index >= 0 && index < elements.size()) { |
| 89 |
return elements.get(index); |
| 90 |
} |
| 91 |
return null; |
| 92 |
} |
| 93 |
|
| 94 |
} |