How can I return a Flux<Order> when my response is wrapped in a json pagination object with Spring 5?

∥☆過路亽.° 提交于 2019-12-06 13:27:47

问题


I've got a web service that I'm trying to consume with the new Spring 5 WebClient.

Working example

# GET /orders/
[
    { orderId: 1, ... },
    { orderId: 1, ... }
]

And the java code for the call

// Java
Flux<Order> ordersStream = webClient.get()
    .uri("/orders/")
    .exchange()
    .flatMap(response -> response.bodyToFlux(Order.class));

Problem

The response from the web service is paginated and therefore doesn't contain the list of items directly as in the example above.

It looks like this

# GET /orders/
{
    "error": null,
    "metadata": {
      "total": 998,
      "limit": 1000,
      "offset": 0
    },
    "data": [
       { orderId: 1, ... },
       { orderId: 2, ... },
    ]
}

How can I get the sub key "data" as a Flux<Order>?

Possible solution, but I don't know if it's the best approach...

Create a wrapper class and convert the wrappers .data to a flux.

But now we need to deserialize the whole response at once, potentially running out of memory.

// Java
Flux<Order> ordersStream = webClient.get()
    .uri("/orders/")
    .exchange()
    .flatMap(response -> response.bodyToMono(PageWrapper.class))
    .flatMapMany(wrapper -> Flux.fromIterable(wrapper.data));

Is there a better way?

来源:https://stackoverflow.com/questions/44478189/how-can-i-return-a-fluxorder-when-my-response-is-wrapped-in-a-json-pagination

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!