I'm building a small micro service to implement a couple of sorting algorithms using Java & Vert.x
One of my requirements is to handle nested lists like [5, [4, 3, 2], 1, [[0]]]
The request body is a JSON object like:
{"arr": [5, [4, 3, 2], 1, [[0]]]}
How can I parse a JSON object/ JSON array with a nested list to a flat list in Java?
// This is how I handle simple lists
private void doBubbleSort(RoutingContext routingContext) {
JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");
// How do I get the size of the list if it is multi-dimensional
int size = jsonArray.size();
int[] unsortedList = new int[size];
for (int i = 0; i < size; i++) {
// Here I want to check whether the current item is an int or
// another nested list. if it is a list, i want to loop over it
// and also add it to the result
unsortedList[i] = jsonArray.getInteger(i);
}
...
}
The result I'm looking for:
int[5, 4, 3, 2, 1, 0]
I know I need to check whether the current value is of type int or list, but struggling to get it working with the type conversions from JSON to int to list.
In Python I can do this without the type conversions.
def flatten_list(arr: list):
nested_arr = deepcopy(arr)
while nested_arr:
sublist = nested_arr.pop(0)
if isinstance(sublist, int):
yield sublist
if isinstance(sublist, list):
nested_arr = sublist + nested_arr