I am trying to organize a complex json config file with multiple layers so that it can be easily read in code.
So I want to convert something like this:
{
"rootProp": {
"a": 1,
"moreObj": {
"b": "beta"
}
}
}
into
{
"rootProp.a": 1,
"rootProp.moreObj.b": "beta"
}
I have a recursive version, but I'm curious if this can be done with streams or with some library.
public JsonObject flattenJson(JsonObject jsonObject) {
return flattenJson(jsonObject, "");
}
public JsonObject flattenJson(JsonObject jsonObject, String prefix) {
JsonObject result = new JsonObject();
jsonObject
.forEach(entry -> {
if (entry.getValue() instanceof JsonArray) {
throw new RuntimeException("Config shouldn't contain arrays");
}
if (entry.getValue() instanceof JsonObject) {
JsonObject value = (JsonObject) entry.getValue();
JsonObject flat = flattenJson(value, entry.getKey() + ".");
flat
.stream()
.forEach(flattenedEntry -> {
String key = prefix + flattenedEntry.getKey();
result.put(key, flattenedEntry.getValue());
});
} else {
String keyName = prefix + entry.getKey();
result.put(keyName, entry.getValue());
}
});
return result;
}