the*_*one 6 spring webclient reactive-programming project-reactor spring-webflux
我正在编写一个简单的 get 方法来从 API URL 检索评论。API 将 json 数据作为字符串返回。返回Mono<Object>会引发错误。请在下面找到 HTTP 响应。
{
"timestamp": "2019-02-05T11:25:33.510+0000",
"path": "Some URL",
"status": 500,
"error": "Internal Server Error",
"message": "Content type 'text/plain;charset=utf-8' not supported for bodyType=java.lang.Object"
}
Run Code Online (Sandbox Code Playgroud)
我发现响应是一个字符串。所以返回Mono<String>工作正常。但我想Mono<MyObject>从 API 响应中返回。
我如何转换Mono<String>为Mono<MyObject>?除了How to get String from Mono<String> in react java之外,我在 google 上找不到任何解决方案。
以下是我的服务类:
@Service
public class DealerRaterService {
WebClient client = WebClient.create();
String reviewBaseUrl = "Some URL";
public Mono<Object> getReviews(String pageId, String accessToken) {
String reviewUrl = reviewBaseUrl + pageId + "?accessToken=" + accessToken;
return client.get().uri(reviewUrl).retrieve().bodyToMono(Object.class);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加我的控制器类:
@RestController
@RequestMapping("/path1")
public class DealerRaterController {
@Autowired
DealerRaterService service;
@RequestMapping("/path2")
public Mono<Object> fetchReview(@RequestParam("pageid") String pageId,
@RequestParam("accesstoken") String accessToken) throws ParseException {
return service.getReviews(pageId, accessToken);
}
}
Run Code Online (Sandbox Code Playgroud)
让我知道您需要更多信息。
这就是我解决问题的方法。使用映射来检索字符串并使用 ObjectMapper 类将该字符串转换为我的 POJO 类。
@Service
public class DealerRaterService {
WebClient client = WebClient.create();
String reviewBaseUrl = "some url";
public Mono<DealerReview> getReviews(String pageId, String accessToken)
throws JsonParseException, JsonMappingException, IOException {
String reviewUrl = reviewBaseUrl + pageId + "?accessToken=" + accessToken;
Mono<String> MonoOfDR = client.get().uri(reviewUrl).retrieve().bodyToMono(String.class);
return MonoOfDR.map(dealerRater -> {
try {
DealerReview object = new ObjectMapper().readValue(dealerRater, DealerReview.class);
return object;
} catch (IOException e) {
e.printStackTrace();
}
return null;
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5810 次 |
| 最近记录: |