Reputation: 1520
I am writing a simple get method to retrieve reviews from an API URL. The API is returning json data as String. Returning Mono<Object>
throws an error. Please find below the HTTP response.
{
"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"
}
I found that the response is a string. So returning Mono<String>
is working fine. But I want to return Mono<MyObject>
from the API response.
How do I convert Mono<String>
to Mono<MyObject>
? I could not find any solutions on google except How to get String from Mono<String> in reactive java.
Below is my service 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);
}
}
Edit: Adding my controller 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);
}
}
Let me know you need any more information.
Upvotes: 6
Views: 9853
Reputation: 1520
This is how I fixed my problem. Used map to retrieve string and converting that string to my POJO class using ObjectMapper 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;
});
}
}
Upvotes: 2