我有一个包含对象的数组的json文件。我想遍历每个对象,并在内部发送一个发帖请求。我的问题是尝试为数组中的每个对象遍历@RequestBody并调用createObj方法。
我将json粘贴到Postman中进行测试 我已经有一个像这样的createObject,但是它适用于Mono而不是
我尝试过这样迭代
@PostMapping(path = "multicreate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Flux<Hospital> createMultipleHospital(@RequestBody Flux<Hospital> hospital) {
hospital.collectList().flatMap(x -> {
return hospitalService.createHospital((Mono<Hospital>) x);
});
return null;
}
// Should loop and send 2 POST request.
[
{
"name": "Miami Cancer Institute",
"address": "8900 North Kendall Drive",
"phone": "786-596-2000",
"zipcode": "33176",
"city": "Miami",
"state": "FL"
},
{
"name": "Mercy Hospital",
"address": "3663 S Miami Ave",
"phone": "305-854-4400",
"zipcode": "33133",
"city": "Miami",
"state": "FL"
}
]
控制器
@PostMapping(path = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Hospital> createHospital(@RequestBody Mono<Hospital> hospital) {
System.out.println(hospital);
return hospitalService.createHospital(hospital);
}
服务/存储库
@Override
public Mono<Hospital> createHospital(Mono<Hospital> hospitalMono) {
return hospitalMono.flatMap(hosp -> {
try {
return reactiveMongoOperations.save(
hosp.createLatCord(hosp));
} catch (InterruptedException | ApiException | IOException e) {
e.printStackTrace();
}
return Mono.just(hosp);
});
}
答案 0 :(得分:1)
在我刚刚将方法返回类型和参数从MONO切换为FLUX并工作之后,解决了该问题。
@Override
public Flux<Hospital> createHospital(Flux<Hospital> hospitalMono) {
return hospitalMono.flatMap(hosp -> {
try {
return reactiveMongoOperations.save(
hosp.createLatCord(hosp));
} catch (InterruptedException | ApiException | IOException e) {
e.printStackTrace();
}
return Mono.just(hosp);
});
}