diff --git a/json-modules/json-2/src/main/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySet.java b/json-modules/json-2/src/main/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySet.java new file mode 100644 index 000000000000..3f7c01b54e39 --- /dev/null +++ b/json-modules/json-2/src/main/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySet.java @@ -0,0 +1,23 @@ +package com.baeldung.jsongetvaluewithkeyset; + +import org.json.JSONObject; +import java.util.Set; +import java.util.HashSet; + +public class JSONGetValueWithKeySet { + public static Set extractKeys(String jsonString) { + JSONObject jsonObject = new JSONObject(jsonString); + return jsonObject.keySet(); + } + + public static void extractNestedKeys(JSONObject jsonObject, String parentKey, Set result) { + for (String key : jsonObject.keySet()) { + String fullKey = parentKey.isEmpty() ? key : parentKey + "." + key; + Object value = jsonObject.get(key); + result.add(fullKey); + if (value instanceof JSONObject) { + extractNestedKeys((JSONObject) value, fullKey, result); + } + } + } +} diff --git a/json-modules/json-2/src/test/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySetUnitTest.java b/json-modules/json-2/src/test/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySetUnitTest.java new file mode 100644 index 000000000000..36ccbd238daa --- /dev/null +++ b/json-modules/json-2/src/test/java/com/baeldung/jsongetvaluewithkeyset/JSONGetValueWithKeySetUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jsongetvaluewithkeyset; + +import org.json.JSONObject; + +import org.junit.Test; +import java.util.Set; +import java.util.HashSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class JSONGetValueWithKeySetUnitTest { + + @Test + public void testExtractFlatKeys() { + String json = "{\"name\":\"Jane\", \"name_id\":12345, \"city\":\"Vancouver\"}"; + Set keys = JSONGetValueWithKeySet.extractKeys(json); + assertTrue(keys.contains("name")); + assertTrue(keys.contains("name_id")); + assertTrue(keys.contains("city")); + assertEquals(3, keys.size()); + } + + @Test + public void testExtractNestedKeys() { + String json = "{" + + "\"user\": {" + + "\"id\": 101," + + "\"name\": \"Gregory\"" + + "}," + + "\"city\": {" + + "\"id\": 121," + + "\"name\": \"Calgary\"" + + "}," + + "\"region\": \"CA\"" + + "}"; + + JSONObject jsonObject = new JSONObject(json); + Set actualKeys = new HashSet<>(); + JSONGetValueWithKeySet.extractNestedKeys(jsonObject, "", actualKeys); + + Set expectedKeys = Set.of("user", "user.id", "user.name", "city", + "city.id", "city.name", "region"); + assertEquals(expectedKeys, actualKeys); + } +}