Using Jackson JSON library, this json may be parsed as a Map<String, Object> using TypeReference:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonTest {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\n"
+ "\"key1\": {\n"
+ " \"key1.1\": {\n"
+ " \"nestedkey1\": \"something\",\n"
+ " \"nestedkey2\": \"something\",\n"
+ " \"nestedkey3\": \"Something\"\n"
+ " },\n"
+ " \"key1.2\": {\n"
+ " \"nestedkey1\": \"something\",\n"
+ " \"nestedkey2\": \"something\",\n"
+ " \"nestedkey3\": \"Something\"\n"
+ " }\n"
+ "},\n"
+ "\"key2\": {\n"
+ " \"key2.1\": {\n"
+ " \"nestedkey1\": \"something\",\n"
+ " \"nestedkey2\": \"something\",\n"
+ " \"nestedkey3\": \"Something\"\n"
+ " },\n"
+ " \"key2.2\": {\n"
+ " \"nestedkey1\": \"something\",\n"
+ " \"nestedkey2\": \"something\",\n"
+ " \"nestedkey3\": \"Something\"\n"
+ " }\n"
+ "}}"; // make sure the json is valid and closing } is available
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<>() {});
System.out.println(map);
}
}
To get the list of all keys, a recursive method needs to be implemented to iterate over the entries of the top-level map and add keys:
public static List<String> getKeys(Map<String, Object> map) {
List<String> keys = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
keys.add(entry.getKey());
if (entry.getValue() instanceof Map) {
Map<String, Object> nested = (Map<String, Object>) entry.getValue();
keys.addAll(getKeys(nested));
}
}
return keys;
}
Similarly, a list of "prefixed" keys may be created:
public static List<String> getPrefixedKeys(String prefix, Map<String, Object> map) {
List<String> keys = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = prefix + entry.getKey();
keys.add(key);
if (entry.getValue() instanceof Map) {
Map<String, Object> nested = (Map<String, Object>) entry.getValue();
keys.addAll(getPrefixedKeys(key + "/", nested));
}
}
return keys;
}
// test
System.out.println(getPrefixedKeys("/", map));
Output:
[/key1, /key1/key1.1, /key1/key1.1/nestedkey1, /key1/key1.1/nestedkey2, /key1/key1.1/nestedkey3,
/key1/key1.2, /key1/key1.2/nestedkey1, /key1/key1.2/nestedkey2, /key1/key1.2/nestedkey3,
/key2, /key2/key2.1, /key2/key2.1/nestedkey1, /key2/key2.1/nestedkey2, /key2/key2.1/nestedkey3,
/key2/key2.2, /key2/key2.2/nestedkey1, /key2/key2.2/nestedkey2, /key2/key2.2/nestedkey3]
"key1-key1.1-nestedkey1": "something"?