0

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

0

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Pendula, thank you, I followed your latest advice. I only removed the getBodyAsJsonArray method since it's deprecated and used routingContext.body().asJsonArray() instead.
You are welcome, updated the answer so it does not contain deprecated method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.