I'm using the latest version of Vert.x (4.3.2) and I wrote and handler for a route that serves a POST method.
Below my code to convert the JSON body of that method to a List of objects:
Class<List<CartLineItem>> cls = (Class<List<CartLineItem>>)(Object)List.class;
List<CartLineItem> itemsToAdd = rc.body().asPojo(cls);
Unforntunately whenever I try to iterate over itemsToAdd
I get the exception: java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.acme.CartLineItem
.
How can I fix this issue without using any other library except Vert.x (I mean .. using Jackson I would provide a TypeReference<List> object)?
CodePudding user response:
In Vert.x 3 there was method that you could use:
Json.decodeValue(result.bodyAsString(), new TypeReference<List<ConditionDTO>>() {});
Since in Vert.x 4 this was removed you will need to use specific class DatabindCodec:
io.vertx.core.json.jackson.DatabindCodec.fromString(result.bodyAsString(), new TypeReference<List<SimpleDTO>>() {})
If you don't want to use external libraries there is an option to iterate over an jsonArray that you have in body assuming body is something like this:
[{"name":"Lazar", "age":27},{"name":"Nikola", "age":33}]
List<SimpleDTO> list = routingContext.body().asJsonArray()
.stream()
.map(json -> Json.decodeValue(json.toString(), SimpleDTO.class))
.collect(Collectors.toList());