首页 > 解决方案 > 将一个对象的通量“转换”为其他对象的通量

问题描述

我在 Java Spring Boot 中使用反应式编程。我正在使用 WebClient 和 .bodyToFlux 从端点获取数据。

该数据的形式为:

{"name":"John Doe","details":{"phone":"1234567890","location":"Antarctica"},"phone":null,"location":null}

^通量是Flux<Information>

我有一个名为的类Information,它具有以下字段和构造函数/get/sets:

String name;
Details details;
String phone;
String location;

我有另一个名为的类Details,它具有以下字段和构造函数/get/sets:

String phone;
String location;

当我使用 WebClient 和 .bodyToFlux 从端点获取数据时,它不会为信息对象本身获取电话和位置字段的数据(它们被获取为空),但它会为电话和位置字段获取数据在 Information 对象中的 Details 对象中。

因此,为了从 Details 对象中获取电话和位置数据以将其存储在 Information 对象的电话和位置字段中,我这样做:

.doOnNext(i -> {
i.setPhone(i.getDetails().getPhone()); 
i.setLocation(i.getDetails().getLocation()
});

所以,然后我得到: {"name":"John Doe","details":{"phone":"1234567890","location":"Antarctica"},"phone":"1234567890","location": “南极洲”}

现在是棘手的部分。我想“摆脱” Information 对象中的 Details 对象,因为我已经从中获得了电话和位置数据。

我有一个重复的类InformationWithoutDetailsObject,它有以下字段和构造函数/get/sets:

String name;
String phone;
String location;

我想转换Flux<Information>Flux<InformationWithoutDetailsObject>. 我将如何实现这一目标?我不能使用阻塞,因为它应该是反应式的。

这是我的代码:

public Flux<InformationWithoutDetailsObject> getInformationStream () throws IOException {
    information = webClient
    .get()
    .uri(url)
    .retrieve()
    .bodyToFlux (Information.class)
    .doOnNext(i ->storeCompanyNameAndResourceType(i));
    
    return information;
}

public void storeCompanyNameAndResourceType(Information information) {
    information.setPhone(information.getDetails.getPhone);
    information.setLocation(information.getDetails.getLocation);
}
    

标签: javaspring-bootreactive-programmingspring-webfluxflux

解决方案


如果其他人想知道,我通过将信息变量设为类型Flux<InformationWithoutDetailsObject>(首先是类型Flux<Information>)来修复它,然后使用 .map 将对象“转换”InformationInformationWithoutDetailsObject对象。

public Flux<InformationWithoutDetailsObject> getInformationStream () throws IOException {
    informationWithoutDetailsObject = webClient
    .get()
    .uri(url)
    .retrieve()
    .bodyToFlux (Information.class)
    .doOnNext(i ->storeCompanyNameAndResourceType(i));
    .map(k -> new InformationWithoutDetailsObject(
    k.getPhone(),
    k.getLocation());
    
    return informationWithoutDetailsObject;
}

public void storeCompanyNameAndResourceType(Information information) {
    information.setPhone(information.getDetails.getPhone);
    information.setLocation(information.getDetails.getLocation);
}

当我没有更改 Flux 类型时,.map(....) 也可以工作,但是是的,请尝试这样做,以防第一种方法由于某种原因不起作用。


推荐阅读