Jackson JsonNode to typed Collection

kag0 :

What is the proper way to convert a Jackson JsonNode to a java collection?

If it were a json string I could use ObjectMapper.readValue(String, TypeReference) but for a JsonNode 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?

Sotirios Delimanolis :

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);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448595&siteId=1