Currently, I am utilizing jdk 1.8 and have a rest endpoint in my Java controller:
@PostMapping("/filters")
public ResponseEntity<StatsDTO> listWithFilter(
@RequestBody(required = false) String filter
) {
try {
...............
}
}
A test snippet for the above controller is passing successfully (receiving the expected result) as shown below:
@Test
public void findReferralTest15() throws IOException {
String result = webClient.post()
.uri(endpoint(helper.entity + "/filters"))
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, clientUser())
.body(BodyInserters.fromObject(buildJsonForQuery15()))
.exchange()
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.expectStatus().isOk()
.expectBody(String.class).returnResult().getResponseBody();
ObjectMapper mapper = new ObjectMapper();
ResponseList referralList = mapper.readValue(result, ResponseList.class);
}
public String buildJsonForQuery15() {
String json = "{\"billType\":{\"INTAKE\":true}}";
return json;
}
However, when trying to integrate with the front end (Angular 7 on TypeScript), I found that I had to call JSON.stringify twice (to convert a JSON object or filter to be submitted as a request body) in order to make it work properly with the backend. Otherwise, the value of the "filter" (in the request body) at the Java controller end was returning null.
The JSON.stringify submitted result from our front end with double conversion looks like this (WHEN IT WORKS):
"{\"billType\":{\"INTAKE\":true}}"
Contrastingly, the result from our front end with single JSON.stringify appears like this (WHEN IT DOESN'T WORK):
{"billType":{"INTAKE":true}}
Question: What data type should the requestBody "filter" be in the Java controller to function correctly with single JSON.stringify?
I attempted using json.org.JsonObject as the datatype for "filter", but it did not yield any difference.
Thank you in advance.
Front-end snippet:
const fullUrl = `${this.referralsUrl}/filters?first=${first}&max=${max}`;
const headerDict = {
"Content-Type": "application/json; charset=utf-8",
Accept: "application/json",
"Access-Control-Allow-Headers": "Content-Type"
};
const headers = new HttpHeaders(headerDict);
if (filters) {
const requestBody = JSON.stringify(filters);
return this.http
.post<Page<ClinAssistReferral>>(fullUrl, JSON.stringify(requestBody), { headers })
.pipe(
map((data: any) => {
...........
}
}