1

I know this question has been asked before but this is a bit different, my map looks like this:

key                       value
a.b.c                       1
a.b.d                       2
e.f                         3

The resulting JSON would look like this:

{
"a": {
    "b": {
        "c": 1,
        "d": 2
    }
},
"e": {
    "f": 3}
}

it would be perfect if there is some library that takes care of this.

EDIT : fixed errors in the resulting JSON

isco
  • 350
  • 4
  • 15
  • 2
    I don't understand the logic between the wanted result and the initial map, please explain. – Tunaki Oct 06 '16 at 08:06
  • the keys of the map represent the fields so a.b.c means that the field "a" has a field "b" which has a field "c" and the value of c is 1 – isco Oct 06 '16 at 08:14
  • 1
    So why is `"d"` under `"a"` in the wanted result, when the map has `a.b.d`? And where did `a.b.d.g` go? – Tunaki Oct 06 '16 at 08:14
  • See also http://stackoverflow.com/questions/20355261/how-to-deserialize-json-into-flat-map-like-structure – Tunaki Oct 06 '16 at 08:16
  • Now your JSON is invalid and there is still no `a.b.d.g` in sight. Please, don't rush your question, take the time. – Tunaki Oct 06 '16 at 08:18
  • it is valid, (a.b.d.g) is deleted as it only complicated the example :) – isco Oct 06 '16 at 08:20

1 Answers1

2

Here you go:

    Map<String, Integer> myMap = new HashMap<>();
    myMap.put("a.b.c", 1);
    myMap.put("a.b.d", 2);
    myMap.put("e.f", 3);

    JSONObject output = new JSONObject();
    for (String key : myMap.keySet()) {
        String[] parts = key.split("\\.");
        Integer value = myMap.get(key);

        JSONObject currentPointer = output;
        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];
            boolean isLeaf = i == parts.length - 1;
            if (currentPointer.keySet().contains(part)) {
                currentPointer = (JSONObject) currentPointer.get(part);
            } else {
                if (isLeaf) {
                    currentPointer.put(part, value);
                } else {
                    JSONObject newNode = new JSONObject();
                    currentPointer.put(part, newNode);
                    currentPointer = newNode;
                }
            }
        }
    }
    return output.toJSONString();
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34