【问题标题】:How to get a json field by name using Spring WebClient?如何使用 Spring WebClient 按名称获取 json 字段?
【发布时间】:2019-07-06 15:42:00
【问题描述】:

我有以下 JSON 响应:

{
    "Count": 1,
    "Products": [
        {
            "ProductID": 3423
        },
        {
            "ProductID": 4321
        }
    ]
}

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

我用过这样的东西

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

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

...retrieve().bodyToMono(ProductResponse.class).block();

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

【问题讨论】:

    标签: json spring response webclient project-reactor


    【解决方案1】:

    retrieve() 之后,您始终可以将.map 您的结果转换为相应的类型。在JsonNodepath()实例方法的帮助下,你可以做到类似于WebTestClientjsonPath()

    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();
    

    【讨论】:

    • 我最终创建了一个“ProductDto”,但我使用了你的方法,它解决了我遇到的另一个问题!谢谢!
    • @Nikolay 很好的答案,它对我有用,但我有一个小细节问题:你为什么选择 's' 作为 lambdas 中的局部变量名?我很好奇它的缩写是什么
    • @Ghoti 和 Chips 代表 JsonNode。
    • @AjayKumar 我知道它代表什么,出于好奇我想知道他为什么选择“s”,它的缩写是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多