[英]Parse multi-dimensional JSON array to flat int list in Java
I'm building a small micro service to implement a couple of sorting algorithms using Java & Vert.x 我正在构建一个小型微服务,以使用Java和Vert.x实施几种排序算法
One of my requirements is to handle nested lists like [5, [4, 3, 2], 1, [[0]]]
我的要求之一是处理嵌套列表,例如
[5, [4, 3, 2], 1, [[0]]]
The request body is a JSON object like: 请求主体是一个JSON对象,例如:
{"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? 如何在Java中将带有嵌套列表的JSON对象/ JSON数组解析为平面列表?
// 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. 我知道我需要检查当前值是int类型还是list类型,但是要使它与从JSON到int到list的类型转换一起努力。
In Python I can do this without the type conversions. 在Python中,我可以执行此操作而无需进行类型转换。
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
According to your answers try the following: 根据您的答案尝试以下操作:
private void doBubbleSort(RoutingContext routingContext) {
JsonObject json = routingContext.getBodyAsJson();
JsonArray jsonArray = json.getJsonArray("arr");
List<?> list = jsonArray.getList();
List<Integer> flatList = list.stream()
.map(this::getOrFlatten)
.flatMap(List::stream)
.collect(Collectors.toList());
// convert List<Integer> to int[]
// ...
}
private List<Integer> getOrFlatten(Object o) {
if(o instanceof Integer) {
return Collections.singletonList((Integer) o);
} else if(o instanceof List) {
List<?> list = (List) o;
return list.stream()
.map(this::getOrFlatten)
.flatMap(List::stream)
.collect(Collectors.toList());
} else {
throw new IllegalArgumentException(o.getClass() + " is not supported at getOrFlatten");
}
}
Here you can find how to convert List to int [] 在这里,您可以找到如何将List转换为int []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.