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

Personalized Pinnacles featuring Angular directive elements displayed on a Bing Maps interface

I've implemented the Bing Maps AJAX Control to showcase a map, and I've crafted an Angular directive specifically for the Pushpins intended on the map: app.directive('myPin', function(){ return { restrict: 'E', ...

Using AngularJS to integrate a function within a component

Hey there, I am facing an issue trying to call a function that is in a component. Let me share the code snippet from my component buttonsController: (function(){ "use strict"; angular .module('my') .component('myButton&ap ...

Is there a way to adjust the starting and ending points of a bezier curve in D3 by utilizing the link generator?

I'm currently working on developing a horizontal hierarchical tree Power BI custom visual using TypeScript and D3. I am utilizing d3's treeLayout for this purpose, and my task is to create a link generator that can plot bezier, step, and diagonal ...

Utilizing Array.every to refine a union of array types, narrowing down the options

I need to narrow down the type of a variable that is a union of different array types in order to run specific code for each type. I attempted to use Array.every along with a custom type guard, but encountered an error in TypeScript stating "This expressio ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

How can specific default values be excluded from serialization in GSON?

Is there a way to instruct JSON to exclude serializing fields with specific default values? One approach could be annotating the fields with a custom annotation and using a TypeAdapter to parse them. However, I'm struggling to figure out how to implem ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Learn the process of extracting a particular value from JSON data and displaying it in HTML by utilizing AngularJS's ng-repeat directive

As a newcomer to angularjs, I am encountering difficulties retrieving and displaying a specific value from a json file in order to showcase it on my view page using angularjs ng-repeat for image source. My goal is to repeat the json file based on a particu ...

Exploring the realm of Angular templating and routing combined with the power

Currently, I am in the process of developing my very first Angular website that involves templating and routing. My goal is to have an image on the page that spans the entire window size minus 70 pixels. //Using Jquery (This particular section functions ...

Custom pagination page size in AngularJS trNgGrid

I have been working on developing an Angular table using trNgGrid. It's functioning fine, but I am looking to incorporate custom pagination where the user can choose the number of page items to display per page. I checked out the TrNgGrid Global Opti ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

Converting Umbraco Json to a CSS class named "[]"

I'm currently using Umbraco with the data-type grid layout and I am trying to add custom settings (CSS classes) to each row/cell. The results are somewhat working, but I want to improve it. Here's the user interface: https://i.stack.imgur.com/iY ...

What is the process of extracting an observable from another observable using the pipe method?

Is there a more efficient way to convert an Observable of Observables into an array of Observables in my pipe method? Here is the scenario: // The type of "observables" is Observable<Observable<MyType>[]> const observables = this.http.get<M ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Tips for utilizing Google/Twitter search on an iPhone with the help of PHP and JSON

<?php header('Content-type: application/json'); $json = file_get_contents("http://twitter.com/status/user_timeline/lindsaylohan.json?count=1"); $temp = json_decode($json); $array = Array(); $array[] = $temp; echo json_encode($array); ?> I& ...

Can we use JSON to effectively compare various variables?

My current task involves comparing running services before and after a reboot on Linux servers. However, I am facing difficulty in getting the output to display the differences. The function I have right now saves the pre/post state to disk. Ideally, I wo ...

Can you explain the distinction between interfaces containing function properties written as "f()" and "f: () =>"?

Let's take a look at two interfaces, A and B: interface A {f(): number} interface B {f: () => number} I have experimented with the following: var a: A = {f: function() {return 1}} var a: A = {f: () => 1} var b: B = {f: function() {return 1}} ...