1

I want to convert this JSON:

{
    "ab.g": "foo2",
    "ab.cd.f": "bar",
    "ab.cd.e": "foo"
}

to this:

{
   "ab": {
      "cd": {
         "e": "foo",
         "f": "bar"
      },
      "g": "foo2"
   }
}

I have found this: Convert javascript dot notation object to nested object but the accepted answer on this post has some language specific syntax and I am not able to rewrite the same logic in Java.

Note: There is no attempt in the question because I have answered this myself - because there is no such question on stackoverflow for Java specifically.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43

1 Answers1

3

Answering my own question:

import io.vertx.core.json.JsonObject;

public class Tester {
    public static void main(String[] args) {
        JsonObject jsonObject = new JsonObject();
        deepenJsonWithDotNotation(jsonObject, "ab.cd.e", "foo");
        deepenJsonWithDotNotation(jsonObject, "ab.cd.f", "bar");
        deepenJsonWithDotNotation(jsonObject, "ab.g", "foo2");
    }

    private static void deepenJsonWithDotNotation(JsonObject jsonObject, String key, String value) {
        if (key.contains(".")) {
            String innerKey = key.substring(0, key.indexOf("."));
            String remaining = key.substring(key.indexOf(".") + 1);

            if (jsonObject.containsKey(innerKey)) {
                deepenJsonWithDotNotation(jsonObject.getJsonObject(innerKey), remaining, value);
            } else {
                JsonObject innerJson = new JsonObject();
                jsonObject.put(innerKey, innerJson);
                deepenJsonWithDotNotation(innerJson, remaining, value);
            }
        } else {
            jsonObject.put(key, value);
        }
    }
}
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43