为了账号安全,请及时绑定邮箱和手机立即绑定

返回 OkHttp 异步结果有问题

返回 OkHttp 异步结果有问题

三国纷争 2023-04-13 10:25:31
我有一个java SDK,它使用OkHttp客户端(4.0.0)从服务器获取令牌IAM并将令牌返回给应用程序。关系可能是这样的:Applicaiton Sync call SDK,SDKAsync call IAM。参考这个答案Java - Retrieving Result from OkHttpAsynchronous GET,the代码如下:异步类:class BaseAsyncResult<T> {private final CompletableFuture<T> future = new CompletableFuture<>();T getResult() {    try {        return future.get();    } catch (InterruptedException | ExecutionException e) {        e.printStackTrace();    }    return null;}void onFailure(IOException e) {    future.completeExceptionally(e);}void onResponse(Response response) throws IOException {    String bodyString = Objects.requireNonNull(response.body()).string();    future.complete(IasClientJsonUtil.json2Pojo(bodyString, new TypeReference<T>() {}));}}Okhttp 调用如下:public void invoke(Request request, BaseAsyncResult result) {        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(@NotNull Call call, @NotNull IOException e) {                result.onFailure(e);            }            @Override            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {                result.onResponse(response);            }        });    }该应用程序使用 sdk 代码,如 iasClient 是 okhttp 客户端的包装器: BaseAsyncResult<AuthenticationResponse> iasAsyncResult = new BaseAsyncResult(); iasClient.invoke(request, iasAsyncResult); AuthenticationResponse result = iasAsyncResult.getResult();错误消息:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to x.x.x.AuthenticationResponse我错过了什么?
查看完整描述

2 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

您需要确保 jackson 知道将值反序列化到哪个类。在这种情况下,您要求 Jackson 将响应反序列化为 TypeReference ,默认情况下它将解析为 Map ,除非您指定类(在本例中为 AuthenticationResponse )。因此, Future 解析为 linkedHashMap 并导致类转换。尝试替换下面的行。

future.complete(IasClientJsonUtil.json2Pojo(bodyString, new TypeReference<T>() {}));

future.complete(IasClientJsonUtil.json2Pojo(bodyString, new TypeReference<AuthenticationResponse>() {}));



查看完整回答
反对 回复 2023-04-13
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

一种方法是将私有类类型变量添加到 BaseAsyncResult,然后在 json2Pojo 函数中使用该类,然后 BaseAsyncResult 可能如下所示:


public class BaseAsyncResult<T> {

    private final CompletableFuture<T> future = new CompletableFuture<>();

    private Class<T> classType;


    public BaseAsyncResult(Class<T> classType) {

        this.classType = classType;

    }


    public T getResult() {

        try {

            return future.get();

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        }

        return null;

    }


    void onFailure(IOException e) {

        future.completeExceptionally(e);

    }


    void onResponse(Response response) throws IOException {

        future.complete(JacksonUtil.json2Pojo(response.body().string(), classType));

    }

}


查看完整回答
反对 回复 2023-04-13
  • 2 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信