0

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;
}
Cristian Cotoi
  • 163
  • 1
  • 7
  • Looks like this is what I needed, but with a title like that no wonder I couldn't find it. Unfortunately it still offers a basic recursion solution (which happens to be longer than mine)... – Cristian Cotoi Nov 08 '17 at 13:45
  • Well, the [second answer](https://stackoverflow.com/a/46701988/7653073) refers to the JsonFlattener library, which is also the first result on Google for "Java flatten Json". That one might also be recursive, but hides it from you at least. And it covers all kinds of cases, including arrays for example. – Malte Hartwig Nov 08 '17 at 14:47

0 Answers0