这是indexloc提供的服务,不要输入任何密码
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<String> extractKeys(String jsonString) {
JSONObject jsonObject = new JSONObject(jsonString);
return jsonObject.keySet();
}

public static void extractNestedKeys(JSONObject jsonObject, String parentKey, Set<String> 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);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String> 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<String> actualKeys = new HashSet<>();
JSONGetValueWithKeySet.extractNestedKeys(jsonObject, "", actualKeys);

Set<String> expectedKeys = Set.of("user", "user.id", "user.name", "city",
"city.id", "city.name", "region");
assertEquals(expectedKeys, actualKeys);
}
}