我已经进入Quarkus并尝试使用Mutiny Vertx WebClient。我的代码可以工作,但我不喜欢依赖不安全/未检查的赋值,这就是我目前在HttpResponse上使用bodyAsJson方法编写代码的方式。有没有更好的方法,或者更标准的方法来从Mutiny Vertx客户端解码JSON?我意识到我可以只调用bodyAsJsonObject并返回它,但我需要对从API调用返回的数据进行处理,所以我需要将其解码为表示数据形状/结构的类。
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("");
}
});
}
}发布于 2020-11-29 04:03:15
有几种方法。首先,Vert.x在幕后使用Jackson,所以可以使用Jackson做的任何事情都是可能的。
您可以使用resp.bodyAsJson(MyStructure.class),这将创建一个MyStructure实例。
如果您有一个JSON数组,则可以将每个元素映射到对象类。
最后,您可以实现自己的body编解码器(请参阅https://vertx.io/docs/apidocs/io/vertx/ext/web/codec/BodyCodec.html)。
https://stackoverflow.com/questions/65046689
复制相似问题