Parse multi-dimensional JSON array to flat int list in Java












0















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









share|improve this question























  • Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

    – aBnormaLz
    Jan 2 at 15:35













  • @aBnormaLz I'm using Java8. thanks

    – krankit
    Jan 2 at 16:28











  • Okay, and how deep the nest can be? only 3 levels? More?

    – aBnormaLz
    Jan 2 at 16:32











  • @aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

    – krankit
    Jan 2 at 16:54
















0















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









share|improve this question























  • Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

    – aBnormaLz
    Jan 2 at 15:35













  • @aBnormaLz I'm using Java8. thanks

    – krankit
    Jan 2 at 16:28











  • Okay, and how deep the nest can be? only 3 levels? More?

    – aBnormaLz
    Jan 2 at 16:32











  • @aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

    – krankit
    Jan 2 at 16:54














0












0








0








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









share|improve this question














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






java json nested vert.x flatten






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 15:13









krankitkrankit

2217




2217













  • Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

    – aBnormaLz
    Jan 2 at 15:35













  • @aBnormaLz I'm using Java8. thanks

    – krankit
    Jan 2 at 16:28











  • Okay, and how deep the nest can be? only 3 levels? More?

    – aBnormaLz
    Jan 2 at 16:32











  • @aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

    – krankit
    Jan 2 at 16:54



















  • Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

    – aBnormaLz
    Jan 2 at 15:35













  • @aBnormaLz I'm using Java8. thanks

    – krankit
    Jan 2 at 16:28











  • Okay, and how deep the nest can be? only 3 levels? More?

    – aBnormaLz
    Jan 2 at 16:32











  • @aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

    – krankit
    Jan 2 at 16:54

















Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

– aBnormaLz
Jan 2 at 15:35







Are you using Java8+ or Java7- ? The second question is how deep the nest can be?

– aBnormaLz
Jan 2 at 15:35















@aBnormaLz I'm using Java8. thanks

– krankit
Jan 2 at 16:28





@aBnormaLz I'm using Java8. thanks

– krankit
Jan 2 at 16:28













Okay, and how deep the nest can be? only 3 levels? More?

– aBnormaLz
Jan 2 at 16:32





Okay, and how deep the nest can be? only 3 levels? More?

– aBnormaLz
Jan 2 at 16:32













@aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

– krankit
Jan 2 at 16:54





@aBnormaLz More than 3. I'm expecting lists of different complexity. Some may be simple [3, 2, 1] and some could have nested elements like [1, [[[[3]]]], 2] or [[1], 2, 3]. But the complexity is not known in advance

– krankit
Jan 2 at 16:54












1 Answer
1






active

oldest

votes


















1














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






share|improve this answer
























  • Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

    – krankit
    Jan 2 at 20:30











  • Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

    – aBnormaLz
    Jan 3 at 9:46











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54008740%2fparse-multi-dimensional-json-array-to-flat-int-list-in-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














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






share|improve this answer
























  • Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

    – krankit
    Jan 2 at 20:30











  • Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

    – aBnormaLz
    Jan 3 at 9:46
















1














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






share|improve this answer
























  • Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

    – krankit
    Jan 2 at 20:30











  • Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

    – aBnormaLz
    Jan 3 at 9:46














1












1








1







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






share|improve this answer













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







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 2 at 17:19









aBnormaLzaBnormaLz

595416




595416













  • Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

    – krankit
    Jan 2 at 20:30











  • Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

    – aBnormaLz
    Jan 3 at 9:46



















  • Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

    – krankit
    Jan 2 at 20:30











  • Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

    – aBnormaLz
    Jan 3 at 9:46

















Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

– krankit
Jan 2 at 20:30





Thanks! Had no idea how to handle the 'unknown' values. The List<?> list = jsonArray.getList(); was exactly what I needed. Will need to dig deeper into java generics

– krankit
Jan 2 at 20:30













Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

– aBnormaLz
Jan 3 at 9:46





Your welcome :) also you can take a look at list.parallelStream(), if you want to run the multiple getOrFlatten calls concurrently.

– aBnormaLz
Jan 3 at 9:46




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54008740%2fparse-multi-dimensional-json-array-to-flat-int-list-in-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

A Topological Invariant for $pi_3(U(n))$