繁体   English   中英

如何使用 Unirest 以列表形式获得回复?

[英]How to get response in list form using Unirest?

我的项目是使用 Spring Boot 框架用 Java 编程语言编写的。 我使用 Unirest 库来获取对某些 API 的请求,并且我想以表单形式获得响应,它看起来像List<SomeResponse>下面我写了一些我尝试制作的请求示例。 为什么我需要一个列表? 因为这种数据结构更方便,并且会在整个庞大项目的其余部分中使用。 我尝试了各种选项来接收对请求的响应,但我无法以任何方式获得List <SomeResponse> 目前,我的努力只让我得到了一个我需要的对象数组。 当然,我们可以尝试将数组转换为列表,但在我看来,在这里,我们会降低速度。

 try {
            SomeResponse[] SomeResponses = Unirest.post(url)
                    .header("Content-Type", "application/json")
                    .header("Authorization", key)
                    .body("[\"" + address + "\"]")
                    .asObject(SomeResponse[].class)
                    .getBody();
            return Result.ok(SomeResponses);
        } catch (UnirestException e) {
            return Result.error("Error in call API " + url);
        }

此外,我还配置了 Jackson 库,该库将 JSON 格式序列化,我们在 POJO 类中收到该格式以响应请求。 也许您可以告诉如何正确配置映射器,以便它可以接受并序列化此响应。

关于库和框架版本的几句话。 我使用 Gradle 来构建和管理依赖项。

org.springframework.boot:spring-boot-starter:2.0.0.RELEASE
com.fasterxml.jackson.core:jackson-databind:2.10.1
com.mashape.unirest:unirest-java:1.4.9

非常感谢你的回答! PS 抱歉,这个问题可能结构不好,但这是我第一次在这个平台上写问题,我保证以后会改进我的问题。

SomeResponse[].class asObjectGenericType<List<SomeResponse>>对象。

try {
    List<SomeResponse> someResponses = Unirest.post(url)
        .header("Content-Type", "application/json")
        .header("Authorization", key)
        .body("[\"" + address + "\"]")
        .asObject(new GenericType<List<SomeResponse>>() {})
        .getBody();
        return Result.ok(someResponses);
 } catch (UnirestException e) {
     return Result.error("Error in call API " + url);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM