Skip to content
Advertisement

Collect all elements in a JSON file into a single list

I am using Gson 2.8.1+ (I can upgrade if needed).

If I have the JsonObject:

"config" : {
        "option_one" : {
            "option_two" : "result_one"
        }
    }
}

… how can I convert this efficiently to the form:

"config.option_one.option_two" : "result_one"

Advertisement

Answer

Simple example:

public static void main(String[] args) {
    String str = """
    {
        "config" : {
            "option_one" : {
                "option_two" : "result_one"
            }
        }
    }""";
    var obj = JsonParser.parseString(str).getAsJsonObject();
    System.out.println(flatten(obj)); // {"config.option_one.option_two":"result_one"}
}

public static JsonObject flatten(JsonObject toFlatten) {
    var flattened = new JsonObject();
    flatten0("", toFlatten, flattened);
    return flattened;
}

private static void flatten0(String prefix, JsonObject toFlatten, JsonObject toMutate) {
    for (var entry : toFlatten.entrySet()) {
        var keyWithPrefix = prefix + entry.getKey();
        if (entry.getValue() instanceof JsonObject child) {
            flatten0(keyWithPrefix + ".", child, toMutate);
        } else {
            toMutate.add(keyWithPrefix, entry.getValue());
        }
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement