The JSON.stringify method in TypeScript/JavaScript does not align with the json-String parameter or request body in a Java controller

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) => {
      ...........
      }
}

Answer №1

In cases where the body remains static, it is recommended to create a Data Transfer Object (DTO) for the request.

However, if the body is dynamic, I would advise experimenting with JsonNode from the Jackson library to handle the variability.

import com.fasterxml.jackson.databind.JsonNode;
...

@PostMapping("/filters")
public ResponseEntity<StatsDTO> listWithFilter(
      @RequestBody(required = false) JsonNode filter
) {
   try { 
      var intake = filter.get("billType").get("INTAKE").asBoolean()
      ...............
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the best way to make a popup link in my situation?

I'm attempting to use Angular to open a popup window in my situation. Here's what I've got: <a ng-href = "window.open('{{videoLink}}')" >open a video</a> When I try this, I get a 'Not found' error in the br ...

Using POST in Android to send a byte array within JSON data

I am facing an issue with my JSON server (WCF REST) and a JSON POST method that requires an object containing id (string) and an image (byte[]): [DataContract(Name = "image")] public class CustomImage { [DataMember(Name = "id")] public string ...

I'm looking to capture a screenshot on the device when a button is clicked. Can someone provide me with the necessary code to achieve this functionality?

I developed a quiz application that displays a certificate with the user's achievements once they have completed the quiz. I am looking to enable the device to automatically take a screenshot of the certificate so that users can easily find it in thei ...

Tips for incorporating confidence intervals into a line graph using (React) ApexCharts

How can I utilize React-ApexCharts to produce a mean line with a shaded region to visually represent the uncertainty of an estimate, such as quantiles or confidence intervals? I am looking to achieve a result similar to: ...

Starting your application with an in-memory database using Spring Boot

I have a basic Spring Boot application that is connected to a Postgres database. The URL and login information can be found in the application.properties file. When I start the application locally for testing, the database must also be running, otherwise ...

Converting a dictionary with Arabic characters to JSON utilizing the json.dumps function

I am working with a dictionary that contains Arabic words such as data = [{'name': 'آدَم'}, {'name': 'آزَر'}] print(json.dumps(data), file=open('data.json', 'a', encoding="utf-8")) When ...

Determine if every object in the array contains a specific key value pair

I am dealing with the following JSON data: { records:{ data:{ current:{ records:{ '2years':[{a:1, b:2, flag:true}, {a:2, b:4}, ...

The element you are trying to click on is not clickable because it is being accessed using

I have encountered a strange issue: When I select an element using the following code: WebElement e1 = driver.findElement(By.xpath("//div1")); WebElement e2 = e1.findElement(By.xpath(".[@class='c2']")); e2.click(); I am unable to click on e2, a ...

I'm having trouble accessing my namespace in TypeScript because it hasn't been properly

After obtaining Visual Studio Community 2015 along with Node.js Tools, I decided to create a "Blank Node.js Console Application" Typescript project. Within this project, I added another TypeScript file named TypeScript1.ts. In this file, I defined the fol ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

Calculating the total cumulative amount from a list of Map

I recently encountered a scenario where I received input containing a list with maps inside it. List<Map<String, String>> actAllSavAccDetLists = test1Page.getAllSavingsAccountsDetails(); // The data looks something like this [ {Savings=Ac ...

When viewing an array, the objects' values are displayed clearly; however, when attempting to access a specific value, it

I am attempting to retrieve the board_id of my objects in the columnsServer array... columnsServer: Column[]; this.service.getColumns() .subscribe(data => { this.columnsServer = data; console.log(this.columnsServer); for (this.i = 0; this.i ...

The type of Object.values() is not determined by a union or Records

When utilizing TypeScript, the Object.values() function encounters issues in deducing the accurate type from a union of Records: type A = Record<string, number>; type B = Record<string, boolean>; function func(value: A | B) { const propert ...

Unable to retrieve data in react/next js despite being able to log it in the console

I am currently utilizing Next Js (React Js) for building my Web app. I have integrated graphql to fetch data from the database successfully, but facing issues in rendering it on the screen. What steps should I take next? import Link from 'next/link&ap ...

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...

The functionality of Layout.tsx is inconsistent across various pages

I'm having trouble with the console.log() code to display the page path only showing up in the "pages.tsx" file (src/app/pages.tsx) and not appearing in the console for other files located in (src/page/Login). Here is the code from layout.tsx: ' ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

Encountering KeyError in my Python code

I am currently working on a Python script to download images. However, I am facing an issue with a KeyError in Python v 2.7.11. Here is my code: import urllib, urllib2, demjson, os json = demjson.JSON() def read_newbooks_file(path): data = open(path) isb ...