java - 使用 Jackson 和 WebClient 将 json 数组反序列化为对象

标签 java spring spring-boot jackson spring-webflux

我在使用 Spring 反序列化 json 数组时遇到问题。 我有来自服务的这个 json 响应:

[
    {
        "symbol": "XRPETH",
        "orderId": 12122,
        "clientOrderId": "xxx",
        "price": "0.00000000",
        "origQty": "25.00000000",
        "executedQty": "25.00000000",
        "status": "FILLED",
        "timeInForce": "GTC",
        "type": "MARKET",
        "side": "BUY",
        "stopPrice": "0.00000000",
        "icebergQty": "0.00000000",
        "time": 1514558190255,
        "isWorking": true
    },
    {
        "symbol": "XRPETH",
        "orderId": 1212,
        "clientOrderId": "xxx",
        "price": "0.00280000",
        "origQty": "24.00000000",
        "executedQty": "24.00000000",
        "status": "FILLED",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "SELL",
        "stopPrice": "0.00000000",
        "icebergQty": "0.00000000",
        "time": 1514640491287,
        "isWorking": true
    },
    ....
]

我使用来自 Spring WebFlux 的新 WebClient 获取此 json,代码如下:

@Override
    public Mono<AccountOrderList> getAccountOrders(String symbol) {
        return binanceServerTimeApi.getServerTime().flatMap(serverTime -> {
            String apiEndpoint = "/api/v3/allOrders?";
            String queryParams = "symbol=" +symbol.toUpperCase() + "&timestamp=" + serverTime.getServerTime();
            String signature = HmacSHA256Signer.sign(queryParams, secret);
            String payload = apiEndpoint + queryParams + "&signature="+signature;
            log.info("final endpoint:"+ payload);
            return this.webClient
                    .get()
                    .uri(payload)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(AccountOrderList.class)
                    .log();
        });
    }

账户订单列表

public class AccountOrderList {

    private List<AccountOrder> accountOrders;

    public AccountOrderList() {
    }

    public AccountOrderList(List<AccountOrder> accountOrders) {
        this.accountOrders = accountOrders;
    }

    public List<AccountOrder> getAccountOrders() {
        return accountOrders;
    }

    public void setAccountOrders(List<AccountOrder> accountOrders) {
        this.accountOrders = accountOrders;
    }
}

AccountOrder 是一个映射字段的简单 pojo。

实际上,当我点击 get 时,它说:

org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize instance of `io.justin.demoreactive.domain.AccountOrder` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `io.justin.demoreactive.domain.AccountOrder` out of START_ARRAY token
 at [Source: UNKNOWN; line: -1, column: -1]

如何使用新的 webflux 模块正确反序列化 json?我究竟做错了什么?

更新 05/02/2018

两个答案都是正确的。他们完美地解决了我的问题,但最后我决定使用稍微不同的方法:

@Override
    public Mono<List<AccountOrder>> getAccountOrders(String symbol) {
        return binanceServerTimeApi.getServerTime().flatMap(serverTime -> {
            String apiEndpoint = "/api/v3/allOrders?";
            String queryParams = "symbol=" +symbol.toUpperCase() + "&timestamp=" + serverTime.getServerTime();
            String signature = HmacSHA256Signer.sign(queryParams, secret);
            String payload = apiEndpoint + queryParams + "&signature="+signature;
            log.info("final endpoint:"+ payload);
            return this.webClient
                    .get()
                    .uri(payload)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToFlux(AccountOrder.class)
                    .collectList()
                    .log();
        });
    }

另一种方法是直接返回 A Flux,这样您就不必将其转换为列表。 (这就是通量:n 个元素的集合)。

最佳答案

关于您对问题的更新答案,使用 bodyToFlux不必要地低效并且在语义上也没有多大意义,因为您真的不想要订单流。您想要的只是能够将响应解析为列表。

bodyToMono(List<AccountOrder>.class)由于类型删除而无法工作。需要能够在运行时保留类型,Spring 提供了ParameterizedTypeReference为此:

bodyToMono(new ParameterizedTypeReference<List<AccountOrder>>() {})

关于java - 使用 Jackson 和 WebClient 将 json 数组反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598233/

相关文章:

java - Java中的Cookie问题

java - Android Sqlite3 - 由命令行创建的列,但不是从我的 Android 代码创建的

spring - 每次tomcat创建新线程时如何运行DelegatingSecurityContextRunnable

java - Freemarker 以错误的方式转换负整数

java - 在 Spring boot App 中获取 h2o MOJO 模型(zip 文件)

java - 过滤嵌套字段,或将类型映射到查询

java - 使用 Jackson 解析嵌套对象

java - JAXB for lists 为 JSON 或 XML 自然返回

java - Spring 。如何将一些变量传递给服务激活器中的方法?

java - 在 Spring Boot 的 application.properties 中使用系统变量