Skip to content

Commit 87c463b

Browse files
authored
BAEL-9249 Code and Unit Tests for Extracting Keys from a JSONObject Using keySet() (#18502)
- Implements the solution showcasing two scenarios: extracting keys from a flat json and from a nested json object. - Provides unit tests for each of the implemented scenarios.
1 parent eaa8a75 commit 87c463b

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.jsongetvaluewithkeyset;
2+
3+
import org.json.JSONObject;
4+
import java.util.Set;
5+
import java.util.HashSet;
6+
7+
public class JSONGetValueWithKeySet {
8+
public static Set<String> extractKeys(String jsonString) {
9+
JSONObject jsonObject = new JSONObject(jsonString);
10+
return jsonObject.keySet();
11+
}
12+
13+
public static void extractNestedKeys(JSONObject jsonObject, String parentKey, Set<String> result) {
14+
for (String key : jsonObject.keySet()) {
15+
String fullKey = parentKey.isEmpty() ? key : parentKey + "." + key;
16+
Object value = jsonObject.get(key);
17+
result.add(fullKey);
18+
if (value instanceof JSONObject) {
19+
extractNestedKeys((JSONObject) value, fullKey, result);
20+
}
21+
}
22+
}
23+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.jsongetvaluewithkeyset;
2+
3+
import org.json.JSONObject;
4+
5+
import org.junit.Test;
6+
import java.util.Set;
7+
import java.util.HashSet;
8+
9+
import static org.junit.Assert.assertEquals;
10+
import static org.junit.Assert.assertTrue;
11+
12+
public class JSONGetValueWithKeySetUnitTest {
13+
14+
@Test
15+
public void givenFlatJson_whenExtractKeys_thenReturnAllTopLevelKeys() {
16+
String json = "{\"name\":\"Jane\", \"name_id\":12345, \"city\":\"Vancouver\"}";
17+
Set<String> keys = JSONGetValueWithKeySet.extractKeys(json);
18+
assertTrue(keys.contains("name"));
19+
assertTrue(keys.contains("name_id"));
20+
assertTrue(keys.contains("city"));
21+
assertEquals(3, keys.size());
22+
}
23+
24+
@Test
25+
public void givenNestedJson_whenExtractNestedKeys_thenReturnAllKeysWithHierarchy() {
26+
String json = "{"
27+
+ "\"user\": {"
28+
+ "\"id\": 101,"
29+
+ "\"name\": \"Gregory\""
30+
+ "},"
31+
+ "\"city\": {"
32+
+ "\"id\": 121,"
33+
+ "\"name\": \"Calgary\""
34+
+ "},"
35+
+ "\"region\": \"CA\""
36+
+ "}";
37+
38+
JSONObject jsonObject = new JSONObject(json);
39+
Set<String> actualKeys = new HashSet<>();
40+
JSONGetValueWithKeySet.extractNestedKeys(jsonObject, "", actualKeys);
41+
42+
Set<String> expectedKeys = Set.of("user", "user.id", "user.name", "city",
43+
"city.id", "city.name", "region");
44+
assertEquals(expectedKeys, actualKeys);
45+
}
46+
}

0 commit comments

Comments
 (0)