Reputation: 658
Suppose I have a JsonObject from javax named jsonObject, which looks like this: {"key":"value"}
How can I get the key name key
?
I only find methods like getJsonString
to get the key value value
, but not the name of the key itself.
Background:
I have a Json Array, which contains key-value pairs. I want to know the name of the key on a specific index i
.
Example:
[{"key1":"value0"},{"key1":"value1"},{"key2","value2"}]
key1
here is a success, key2
is a fail and has to be checked.
Upvotes: 0
Views: 4905
Reputation: 9844
JsonObject
implements Map<String, JsonValue>
. You can call jsonObject.keySet()
to access the keys, or call jsonObject.entrySet()
to get a complete view of the object including both keys and values.
for (String key: jsonObject.keySet()) {
System.out.println(key);
}
In the context of the problem you described, it sounds like you'll want to validate that each array element contains an object with exactly one key-value pair. Perhaps something like this:
Set<Map.Entry<String, JsonValue>> kvPairs = jsonObject.entrySet();
if (kvPairs.size() == 1) {
for (Map.Entry<String, JsonValue> kvPair: kvPairs) {
if (kvPair.getKey().equals("key1")) {
// success
} else {
// error handling
}
}
} else {
// error handling
}
Upvotes: 3