如何使用Spring WebClient按名称获取json字段? [英] How to get a json field by name using Spring WebClient?

查看:310
本文介绍了如何使用Spring WebClient按名称获取json字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON响应:

I have the following JSON Response:

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

我希望能够使用WebClient从Products数组中返回产品"列表,而不必使用"ArrayList products"字段创建单独的Dto类.

I want to be able to return a List of "Product" from the Products array using WebClient without having to create a separate Dto class with the field 'ArrayList products'

我用了这样的东西

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

它检索其中包含一个Product的列表,但所有值都为null.我能够使其与DTO响应(如

It retrieves a List with one Product in it but all the values null. I am able to get it to work with a DTO response such as

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

其中ProductResponse中具有产品列表.但是我试图避免不得不创建额外的类.有没有办法像使用jsonPath(类似于WebTestClient)那样拉出字段?

Where the ProductResponse has the List of Products in it. But I am trying to avoid having to create the extra class. Is there a way to pull the field similar to using jsonPath (similar to WebTestClient)?

推荐答案

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

after retrieve() you can always .map your result to corresponding type. With the help of JsonNode path() instance method you can do it similar to 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();

这篇关于如何使用Spring WebClient按名称获取json字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆