| 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.util.AbstractMap.SimpleImmutableEntry; |
| 9 |
import java.util.ArrayList; |
| 10 |
import java.util.Map.Entry; |
| 11 |
|
| 12 |
/** |
| 13 |
* JSON object. |
| 14 |
*/ |
| 15 |
public final class JSONObject extends JSONValue { |
| 16 |
|
| 17 |
private final ArrayList<SimpleImmutableEntry<String, JSONValue>> members = new ArrayList<>(); |
| 18 |
|
| 19 |
JSONObject() { |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Add a key-value pair. |
| 24 |
* |
| 25 |
* @param name the key |
| 26 |
* @param value the value |
| 27 |
*/ |
| 28 |
void addMember(String name, JSONValue value) { |
| 29 |
members.add(new SimpleImmutableEntry<>(name, value)); |
| 30 |
} |
| 31 |
|
| 32 |
@Override |
| 33 |
public void addTo(JSONTarget<?> target) { |
| 34 |
target.startObject(); |
| 35 |
for (SimpleImmutableEntry<String, JSONValue> member : members) { |
| 36 |
target.member(member.getKey()); |
| 37 |
member.getValue().addTo(target); |
| 38 |
} |
| 39 |
target.endObject(); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Returns the value. |
| 44 |
* |
| 45 |
* @return the value |
| 46 |
*/ |
| 47 |
@SuppressWarnings("unchecked") |
| 48 |
public Entry<String, JSONValue>[] getMembers() { |
| 49 |
return members.toArray(new Entry[0]); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Returns value of the first member with the specified name. |
| 54 |
* |
| 55 |
* @param name |
| 56 |
* name of the member |
| 57 |
* @return value of the first member with the specified name, or |
| 58 |
* {@code null} |
| 59 |
*/ |
| 60 |
public JSONValue getFirst(String name) { |
| 61 |
for (SimpleImmutableEntry<String, JSONValue> entry : members) { |
| 62 |
if (name.equals(entry.getKey())) { |
| 63 |
return entry.getValue(); |
| 64 |
} |
| 65 |
} |
| 66 |
return null; |
| 67 |
} |
| 68 |
|
| 69 |
} |