java - 将一个对象的通量“转换”为其他对象的通量
问题描述
我在 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);
}
解决方案
如果其他人想知道,我通过将信息变量设为类型Flux<InformationWithoutDetailsObject>
(首先是类型Flux<Information>
)来修复它,然后使用 .map 将对象“转换”Information
为InformationWithoutDetailsObject
对象。
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(....) 也可以工作,但是是的,请尝试这样做,以防第一种方法由于某种原因不起作用。
推荐阅读
- botframework - 有没有办法使用自适应卡实现呼叫功能(打开拨号器)?
- python - 如何让机器人在每个命令中给出不同的值
- python - 访问 JSON 对象中的元素
- php - 有没有办法减少循环次数
- php - set_exception_handler 未捕获类异常
- node.js - 在 node_modules/pino/pino.js:9 const { assertDefaultLevelFound, mappings, genLsCache } = require('./lib/levels') 中出现错误
- php - 使用 New Relic Infrastructure 代理的多行应用程序日志解析器
- python - Pandas Dataframe 3D 曲面图
- sql - 我在写游标时收到错误 ORA-01001 无效游标显示偶数条记录
- javascript - 如何在JSX中仅链接一个.map数组的一个元素