【问题标题】:How to deserialize nested JSON array to Flux with Spring WebClient?如何使用 Spring WebClient 将嵌套的 JSON 数组反序列化为 Flux?
【发布时间】:2017-10-27 17:21:32
【问题描述】:

我在 Spring Boot (2.0.0.M1) 应用程序中使用 org.springframework.web.reactive.function.client.WebClient 来查询返回嵌套数组的 REST 接口:

[
    [ "name1", 2331.0, 2323.3 ],
    [ "name2", 2833.3, 3838.2 ]
]

我现在正尝试将此响应映射到 Flux 的对象。为此,我进行了以下调用:

WebClient webClient = WebClient.create("http://example.org");

Flux<Result> results = webClient.get().uri("/query").
    accept(MediaType.APPLICATION_JSON_UTF8).
    exchange().
    flatMapMany(response -> response.bodyToFlux(Result.class));

Result 类看起来像这样:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.math.BigDecimal;

@Data
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class Result {

    private final String name;
    private final BigDecimal value1;
    private final BigDecimal value2;

    @JsonCreator
    public Result(
        @JsonProperty String name,
        @JsonProperty BigDecimal value1,
        @JsonProperty BigDecimal value2) {
        this.name = name;
        this.value1 = value1;
        this.value2 = value2;
    }
}

不幸的是,我收到以下错误:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json;charset=utf-8' not supported

谁能告诉我我做错了什么,或者告诉我一个更好的方法将这种响应反序列化为 Flux,最好以非阻塞方式?

【问题讨论】:

    标签: java json spring-boot project-reactor spring-webflux


    【解决方案1】:

    问题与Flux无关。

    Jackson 根本无法反序列化您的 json 对象,并且可能无法通过 public Result(@JsonProperty String name, @JsonProperty BigDecimal value1, @JsonProperty BigDecimal value2) 使用不同值的数组来反序列化。

    最简单的解决方法是使用下一个构造函数实现。

    @JsonCreator
    public Result(Object[] args) {
         this.name = String.valueOf(args[0]);
         this.value1 = new BigDecimal(String.valueOf(args[1]));
         this.value2 = new BigDecimal(String.valueOf(args[2]));
    }
    

    【讨论】:

    • 我也有同样的问题;但是上面的答案对我不起作用。任何人都可以帮忙吗?谢谢
    • 请在 SO 上发布单独的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多