如何将 Mono<String> 转换为 Mono<MyObject>?

How to convert Mono<String> to Mono<MyObject>?

我正在编写一个简单的 get 方法来从 API URL 检索评论。 API 将 returning 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"
}

我发现响应是一个字符串。所以 returning Mono<String> 工作正常。但我想 return Mono<MyObject> 来自 API 响应。

如何将 Mono<String> 转换为 Mono<MyObject>?除了 .

,我在 google 上找不到任何解决方案

以下是我的服务class:

@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);
    }
}

编辑:添加我的控制器class:

@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);
    }
}

让我知道您需要更多信息。

这就是我解决问题的方法。使用 map 检索字符串并使用 ObjectMapper class.

将该字符串转换为我的 POJO class
@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;
        });

    }

}