The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function:

@PostMapping(path = "ts/sts")
    public void saveTestStep(@RequestBody TestStepDTO testStepDTO){
        TestStep testStep = new TestStep(testStepDTO.getTestCaseId(),
                testStepDTO.getStepNumber(),
                testStepDTO.getDescription(),
                testStepDTO.getTestdata(),
                testStepDTO.getPrerequisite(),
                testStepDTO.getResult());
        TestStepService testStepService = new TestStepService();
        testStepService.save(testStep);
    }

Here is the JavaScript code I use to make the call:

for(i=0;i<prerequisites.length;i++){

                        b = i+1;
                        $.ajax({
                            url: 'http://localhost:8080/ts/sts',
                            dataType: 'json',
                            type: 'post',
                            contentType: 'application/json',
                            data: [{ "result": result[i], "stepNumber": b, "description":  description[i],"testCaseId": 1 , "testdata": testdata[i], "prerequisite": prerequisites[i]}] ,
                            processData: false,
                            success: function( data, textStatus, jQxhr ){
                                $('#response pre').html( JSON.stringify( data ) );
                            },
                            error: function( jqXhr, textStatus, errorThrown ){
                                console.log( errorThrown );
                                console.log("testcaseid: " + testcaseid);
                            }
                        });
                    }

Showing here is the DTO class structure:

public class TestStepDTO {

    @NotBlank
    private Integer testCaseId;
    @NotBlank
    private Integer stepNumber;
    @NotBlank
    private String description;
    @NotBlank
    private String result;
    @NotBlank
    private String testdata;
    @NotBlank
    private String prerequisite;

    // Getters and setters for each field
}

But upon running, I encounter this issue:

2021-04-01 18:49:06.043  WARN 28296 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `b...

If anyone sees or knows where I might be going wrong in this process, any help would be greatly appreciated!

Answer №1

To fix the issue, you need to eliminate the square brackets from your data line in the ajax post call.

data: [{ "result": result[i]... }] 

The corrected version should look like this:

data: { "result": result[i] ... }

The problem arose because the use of square brackets [] signifies an array, while curly brackets {} indicate object notation when sending json to the API.

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 is the best way to add a simple Search bar to the Material UI Data Grid component?

If we take a look at this data grid example: check it out here I'd like to incorporate a simple search bar similar to the one shown here Can someone provide guidance on how to add this feature to Data Grid MUI? ...

The ReactJS component is unable to resolve the specified domain name

Whenever I utilize a component like const React = require('react'); const dns = require('dns'); class DnsResolver extends React.Component { componentDidMount() { dns.resolve('https://www.google.com', (err, addres ...

Transfer properties to the children of this component

I'm a beginner with React and facing an issue when trying to pass custom props to this.props.children. I attempted using React.cloneElement, and while I can see the prop in the console.log within the class where I created it, it seems to get lost duri ...

Leveraging Trustpilot TrustBoxes within a Next.js environment

I'm currently implementing a Trustpilot TrustBox into a Next.js application. Inside my componentDidMount, I have the following code: var trustbox = document.getElementById('trustbox'); window.Trustpilot.loadFromElement(trustbox); In the ...

What is the best way to verify the JSON request in a Spring Boot application?

I need to verify the JSON request I receive from the client side. Despite successfully using annotations like @notnull and @length(min=1,max=8), I am struggling to access the specific fields and error messages that are triggered when validation fails. Alth ...

The development of the React app will pause momentarily upon encountering a single low-severity vulnerability. To address this, you can either run `npm audit fix` to resolve it, or use `npm audit` to gain

A challenge arises while executing the command below in Visual Studio Code to develop a react app: create-react-app my-first-react-app The process halts and displays this message: found 1 low severity vulnerability run `npm audit fix` to rectify th ...

What is the process for accessing information from Symantec through their API?

Experiencing a 400 status code error currently. Feeling a bit stuck on what steps to take next. The 400 status code typically relates to syntax issues. How can I properly format my output into JSON file structure? import requests, json, urllib3 urllib3.d ...

Can ng-submit be overridden?

Is there a way to modify ng-submit in order to execute certain functions before running the expression it contains? For instance, I want to: 1) Mark all fields as dirty or touched so that validation is performed on all fields, even if the user skipped som ...

My goal is to implement a confirmation modal prior to any route changes within Next.js framework

Below is the code block that I have: const onRouteChangeStart = React.useCallback(() => { if (formState.isDirty) { if (window.confirm('Confirmation message')) { return true; } NProgress.done(); throw "A ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Utilizing strings as data in Google charts with jQuery

When working with google charts, the code for generating a chart often looks something like this: var data = new google.visualization.DataTable(); data.addColumn('string', 'Topping'); data.addColumn('number', 'Slices&apo ...

Can you provide instructions on integrating bootstrap 5.02 using npm and webpack?

Trying to bundle my webapp with webpack, but struggling with importing the bootstrap code. I've already spent hours troubleshooting this. Ever since setting up webpack, things haven't been working as they did before. And now, I keep encountering ...

Ensure you are focusing on elements exclusively contained within the parent table and not any child tables nested within its cells

Looking for some help with a unique situation here. I'm struggling to find the right selector for this task. For reference, you can check out the jsfiddle at this link: http://jsfiddle.net/NZf6r/1/ The scenario is that I have a parent table containin ...

Repeat the most recent AJAX request executed

I am currently working on refreshing a specific section of my application which is generated by an AJAX call. I need to target the most recent call that was made and rerun it with the same parameters when a different button is clicked. The data was initial ...

Is it common in Node.js to create multiple instances of "server" objects, but only connect one to a port?

After finishing "Node.js in Action", I'm now piecing together the concepts of Node.js, Connect, and Express. My inquiry revolves around the creation of servers in Node. node_server = http.createServer(); connect_app = Connect(); express_app = Express ...

Is there a way to identify if a user originated from a Google ad and determine if this is their nth page during the session using JavaScript code?

Is there a way for me to execute specific logic when a user, who arrived at the page via a contextual advertisement, reaches a certain page during their session? How can I make this happen? ...

Navigating through web pages and creating dynamic interfaces is made simple

As someone relatively new to React, I am currently exploring how to integrate React Router with Material UI. In my Layout file, I have implemented a Navigation drawer from Material UI with the menu on the left and content on the right, as depicted in the ...

"Utilizing the power of ng-click to target specific child

I am facing an issue with my owl carousel where events are not firing on cloned items. In search of a solution, I came across a suggestion from Stack Overflow to move the event handler from the direct target to its parent element: Original code snippet: ...

Running code step by step in VSCode debugging

After finding answers and solutions partially related to this specific question, I have now established the following launch configurations for debugging my react-redux + electron application. { "version": "0.2.0", "configurations": [ { "typ ...

Angular: When $scope variable is modified, a blank page issue arises

In my Angular application, I have a template called viewAll.html that is displayed after clicking on a link. This template fetches data via AJAX using scope variables. However, I encountered an issue where updating these scope variables through AJAX cause ...