Converting JsonNode to java array Converting JsonNode to java array json json

Converting JsonNode to java array


Moving my comment to an answer, as it got upvoted a lot.

This should do what the OP needed:

new ObjectMapper().convertValue(jsonNode, ArrayList.class)


A quick way to do this using the tree-model... convert the JSON string into a tree of JsonNode's:

ObjectMapper mapper = new ObjectMapper();JsonNode rootNode = mapper.readTree("...<JSON string>...");

Then extract the child nodes and convert them into lists:

List<Double> x = mapper.convertValue(rootNode.get("x"), ArrayList.class);List<Double> y = mapper.convertValue(rootNode.get("y"), ArrayList.class);

A slight longer, but arguable better way to do this is to define a class representing the JSON structure you expect:

public class Request {    List<Double> x;    List<Double> y;}

Then deserialized directly as follows:

Request request = mapper.readValue("...<JSON string>...", Request.class);


"... how do I convert the json object into a java array"

import com.google.common.collect.Streams;public void invoke(JsonNode event) {                     Streams.stream(event.withArray("x").elements())        .forEach( num -> Logger.info(num.asDouble()) )}

The trick is to first get the Iterator object using "elements()" method, then using Guava "stream" method get the stream. Once you have the stream you can do all kinds of array operations(e.g. filter, map) to consume your data.