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

How to extract the text from a WYSIWYG text area inside an iframe using Selenium WebDriver

How can I extract text entered in a WYSIWYG iframe text area? // Entering text for the Message field ContactUs_Page.txt_keyInMessage().sendKeys(ColMessage); ContactUs_Page.java public static WebElement txt_keyInMessage() throws Exception{ try{ ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Unable to replicate the JSON data block

I've been attempting to duplicate the condition block from id 106 to id 107 using the script below, but I keep encountering an error stating "ConvertFrom-Json: Invalid JSON primitive:". Is there something important that I am overlooking? Any guidance ...

How can I center the window vertically based on the middle of an element?

Hey guys, I need some help with my code. I've been trying to create a button that will shift the window's Y position to center the "Box - 5" div vertically through an onclick event. Basically, I want to make sure the "Box - 5" div is positioned i ...

Retrieving JSON information from an external source using ajax

I am currently manually importing JSON data to test with a bootstrap table, but I would like to be able to fetch it from an external file instead. Previously, I was doing this: $(document).ready(function() { $('#content').dataTable( ...

How to sort Django models based on the value in a JSON field

When querying models, I receive a list of evaluated objects from the queryset. One of the fields in these models is a text field containing a JSON string. My goal is to sort this list based on a specific key within the JSON data. Here's an example of ...

Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed. I have placed both buttons outside of the div like this: <button type="button" id="cro ...

Setting URL parameters in a POST request: A guide

Currently, the data in question is structured as JSON within this code snippet. However, I've received feedback indicating that it should actually be implemented as URL parameters. I'm currently facing some difficulties with modifying this to fit ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Scala iterator not functioning correctly with Java

I'm currently working on using restfb to fetch a user's likes from Facebook. After referring to the official documentation, I noticed that the iterator should support paging, but for some reason, it's not functioning as expected in my Scala ...

JavaScript barcode data input

I am working with 2 inputs - #barcode and #quantity. When using a barcode scanner, I can easily enter the quantity after scanning data by pressing the Tab key. Typically, the quantity is null, indicating one piece. Currently, my cursor is in the #quantity ...

Sending both File and Json data to a web API using HttpClient

I am having trouble sending file and JSON data from HttpClient to a web API server. I can access the JSON in the server as a JSON variable, but not through the payload. public class RegulationFilesController : BaseApiController { public void ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

The module 'react/lib/React' could not be located within the file 'ReactTestUtils.js'

Setting up unit-tests for a React Native project using ReactTestUtils is causing an issue with npm test. The error message I receive is: Cannot find module 'react/lib/React' from 'ReactTestUtils.js' I suspect that my dependencies are ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

Enhancing ReactJS functionality by incorporating custom logic prior to resolving promises

In one of my components, there is a function as follows: this.props.firebase.getDropSites("123456").then(data => { console.log(data); }); This function in turn calls the following method from my utilities class: getDropSites(dropSiteId) { return th ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...