如何使用 Spring WebClient 按名称获取 json 字段?

Joe*_*e A 5 spring json webclient response project-reactor

我有以下 JSON 响应:

{
    "Count": 1,
    "Products": [
        {
            "ProductID": 3423
        },
        {
            "ProductID": 4321
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使用 WebClient 从 Products 数组中返回一个“Product”列表,而不必创建一个带有“ArrayList products”字段的单独的 Dto 类

我用过这样的东西

        webClient.get()
                .uri(uriBuilder -> uriBuilder
                .path(URI_PRODUCTS)
                .build())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToFlux(Product.class)
                .collectList();
Run Code Online (Sandbox Code Playgroud)

它检索一个包含一个产品的列表,但所有值都为空。我能够让它与 DTO 响应一起工作,例如

...retrieve().bodyToMono(ProductResponse.class).block();
Run Code Online (Sandbox Code Playgroud)

ProductResponse 中包含产品列表。但我试图避免创建额外的类。有没有办法类似于使用jsonPath(类似于WebTestClient)来拉取字段?

Nik*_*sev 6

之后retrieve()您始终可以将.map结果转换为相应的类型。借助JsonNode path()实例方法,您可以执行类似于WebTestClient jsonPath()

webClient.get()
            .uri(uriBuilder -> uriBuilder
                .path(URI_PRODUCTS)
                .build())
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(JsonNode.class)
            .map(s-> s.path("Products"))
            .map(s->{
                try {
                    return mapper.readValue(s.traverse(), new TypeReference<List<Product>>() {} );
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ArrayList<Product>();
                }
            })
            .block();
Run Code Online (Sandbox Code Playgroud)

  • 我最终创建了一个“ProductDto”,但我使用了你的方法,它解决了我遇到的另一个问题!谢谢你! (2认同)