kag0 kag0 - 1 month ago 5
Java Question

Jackson JsonNode to typed Collection

What is the proper way to convert a Jackson

to a java collection?

If it were a json string I could use
ObjectMapper.readValue(String, TypeReference)
but for a
the only options are
ObjectMapper.treeToValue(TreeNode, Class)
which wouldn't give a typed collection, or
ObjectMapper.convertValue(Object, JavaType)
which feels wrong on account of its accepting any POJO for conversion.

Is there another "correct" way or is it one of these?


Acquire an ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode).

For example, to get a List<String> out of a JSON array containing only JSON strings

ObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
// use it
List<String> list = reader.readValue(arrayNode);