如何将Mono <string>转换为Mono <myobject>?

时间:2019-02-05 11:50:30

标签: spring reactive-programming webclient spring-webflux project-reactor

我正在编写一个简单的get方法,以从API URL检索评论。 API将JSON数据作为String返回。返回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"
}

我发现响应是一个字符串。因此,返回Mono<String>可以正常工作。但是我想从API响应中返回Mono<MyObject>

如何将Mono<String>转换为Mono<MyObject>?除了How to get String from Mono<String> in reactive 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);
    }
}

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

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

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

1 个答案:

答案 0 :(得分:0)

这就是我解决问题的方式。使用地图检索字符串,然后使用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;
        });

    }

}