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.

1 Answer 1

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Very useful, just remove the System.out.println statements from the main method as you're trying to print a function with void return type
EXACTLY what I was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.