Quarkus Mutiny Web Client Decode JSON safely

934 views Asked by At

I've been getting into Quarkus and trying to utilize the Mutiny Vertx WebClient. My code works but I prefer not to have to rely on unsafe/unchecked assignments which is how I've currently written the code with bodyAsJson method on HttpResponse. Is there a better way, or more standard way to decode JSON from the Mutiny Vertx client? I realize I could just call bodyAsJsonObject and return that, but I need to do processing on the data the comes back from API calls so I need to decode it to a class representing the data shape/structure.

package com.something.app.language;

import com.something.app.model.Language;
import io.micrometer.core.annotation.Timed;
import io.smallrye.mutiny.Uni;
import io.vertx.mutiny.core.Vertx;
import io.vertx.mutiny.ext.web.client.WebClient;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.List;

@ApplicationScoped
public class LanguageService {

    @Inject
    Vertx vertx;

    private WebClient client;

    @PostConstruct
    void init() {
        this.client = WebClient.create(vertx);
    }

    @Timed
    public Uni<List<Language>> getLanguages() {
        return this.client
                .get(80, "somehost.com", "/languages")
                .timeout(1000)
                .send()
                .onItem()
                .transform(resp -> {
                   if (resp.statusCode() == 200) {
                       return resp.bodyAsJson(List.class);
                   } else {
                       throw new RuntimeException("");
                   }
                });
    }
}
1

There are 1 answers

0
Clement On

There are several ways. First, Vert.x uses Jackson under the hood, so everything that can be done with Jackson is possible.

You can use resp.bodyAsJson(MyStructure.class), which would create an instance of MyStructure.

If you have a JSON Array, you can map every element to the object class.

Finally, you can implement your own body codec (See https://vertx.io/docs/apidocs/io/vertx/ext/web/codec/BodyCodec.html).