Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Jackson JsonNode array to Java List<String>

Tags:

java

json

jackson

I hava a Jackson JsonNode (v2.6.3) which has a json array as one of its fields and I'm looking to convert that array to a java List

Currently im doing the following problem is line 3:

JsonNode jsonNode = getJsonPayload();
JsonNode partial = jsonNode.path("someArrayField");
List<String> z = new ObjectMapper().readValue(partial.traverse(), new TypeReference<ArrayList<String>>(){}); // <- this is the problem area

This feels expensive and improper I would have thought the library would provide a simple call to achieve this.

What would be the proper/efficient way of obtaining the List? I've seen a few others follow the same pattern as I did above but the answers are not widely accepted

like image 962
Marquis Blount Avatar asked Aug 08 '26 03:08

Marquis Blount


1 Answers

Since Jackson 2.11 methods readerForListOf and readerForArrayOf are available. Thus your code will look like the following:

JsonNode jsonNode = getJsonPayload();
JsonNode partial = jsonNode.path("someArrayField");
List<String> z = new ObjectMapper().readerForListOf(String.class).readValue(partial);
like image 132
Nolequen Avatar answered Aug 10 '26 18:08

Nolequen