Jackson JsonNode for collection collection

What is the correct way to convert Jackson JsonNode to java collection?

If it were a json string, I could use ObjectMapper.readValue(String, TypeReference) , but for JsonNode only parameters are ObjectMapper.treeToValue(TreeNode, Class) , which would not produce a typed collection, or ObjectMapper.convertValue(Object, JavaType) , which feels wrong due to its adoption of POJO for conversion.

Is there another β€œright” way or one of them?

+5
source share
2 answers

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

For example, to get a List<String> from 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); 
+11
source

The ObjectMapper.convertValue () function is convenient and type aware. It can perform a wide range of conversions between tree nodes and Java types / sets and vice versa.

An example of how you can use it:

 List<String> list = new ArrayList<>(); list.add("one"); list.add("two"); Map<String,List<String>> hashMap = new HashMap<>(); hashMap.put("myList", list); ObjectMapper mapper = new ObjectMapper(); ObjectNode objectNode = mapper.convertValue(hashMap, ObjectNode.class); Map<String,List<String>> hashMap2 = mapper.convertValue(objectNode, HashMap.class); 
0
source

All Articles