Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

**

Latest Code Update

**

My JavaScript and Ajax Implementation:

$(function() {
        $("#create_obd").bind("click", function(event) {

            var soNumber = [];

             $('#sales_order_lineItems input[type=checkbox]:checked').each(function(index) { 

               var row = $(this).parent().parent();
               var rowcells = row.find('td');

                var soRowData = {
                       so_number:rowcells[1].innerText
                    };
               soNumber.push(soRowData);

             }); //loop ends

            var soNumbers = JSON.stringify(soNumber);
            alert(soNumbers);
             $.ajax({
                    type: "POST",
                    url: server_ip_address + "/createobdaction",
                    data: soNumbers,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data){alert(data);},
                    failure: function(errMsg) {
                        alert(errMsg);
                    }
                });
            });
    });

Java Code snippet:

package com.app.action;

import java.util.List;

import com.app.bean.SONumber;

public class CreateOBDAction {

private List<SONumber> soNumbers;

public String createOBD() {
    System.out.println(soNumbers.size());
    return "jsonCreateOBDSuccess";
}

public List<SONumber> getSoNumbers() {
    System.out.println("Getter................");
    return soNumbers;
}

public void setSoNumbers(List<SONumber> soNumbers) {
    System.out.println("Setter............");
    this.soNumbers = soNumbers;
}

}

Bean Class Definition

package com.app.bean;

public class SONumber {

    String soNumber;

    public String getSoNumber() {
        return soNumber;
    }

    public void setSoNumber(String soNumber) {
        this.soNumber = soNumber;
    }
}

Struts Configuration (struts.xml)

<action name="createobdaction" class="com.app.action.CreateOBDAction" 
      method="createOBD">
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="json">
        <param name="enableSMD">true</param>
    </interceptor-ref>       
    <result name="jsonCreateOBDSuccess" type="json" />
</action>

Error Handling Scenario

15:32:00,092 ERROR JSONInterceptor:34 - Unable to deserialize JSON object from request 15:32:00,093 DEBUG Dispatcher:80 - Exception occurred during processing request: Unable to deserialize JSON object from request org.apache.struts2.json.JSONException: Unable to deserialize JSON object from request at org.apache.struts2.json.JSONInterceptor.intercept(JSONInterceptor.java:117)

Answer №1

  • Make sure to integrate the Struts2-JSON-plugin into your project;
  • Define properties, getters and setters for each attribute of the JSONized object received from the page;
  • Include the JSON Interceptor in the Interceptor Stack utilized by your action.
  • That's all you need to do.

According to the documentation:

When the interceptor is applied, the action will be filled from the JSON data in the request, following these guidelines:

  1. The "content-type" should be set to "application/json"
  2. The JSON data must be valid, refer to json.org for syntax rules.
  3. Action must contain a public "setter" method for the fields to be filled.
  4. Supported data types for filling include: Primitives (int, long, String...), Date, List, Map, Primitive Arrays, Other classes (more details later), and Array of Other classes.
  5. Any object in JSON that needs to be filled inside a list or map will be treated as type Map (mapping from properties to values), any whole number will be considered Long, any decimal number will be seen as Double, and any array will be a List.

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

Node.JS has deceived us with its false promises of `import` support

Could it be that I am making a mistake? I have been eagerly awaiting the experimental ES6 module loader in Node.JS since version 10. This feature is crucial for me to seamlessly use the same code in both the browser and node environments. This is how I w ...

Utilizing Javascript and CSS for horizontal alignment from left to right

I have a JavaScript function that generates a list of store locations and creates a DIV beneath the map. Currently, the items are displayed top to bottom on the page. However, I would like to change the layout so that the items are shown as 3 in a row fro ...

Save the HTML elements in an object and then use the ng-include directive to include the template

Currently experimenting with this code snippet: var CustomTable = function($elem) { this.properties.element = $elem; this.initialize(); }; CustomTable.prototype.PROPERTIE = { secondElement: $('.second') // this element ...

Display radio options when clicked upon

I am in the process of creating a set of radio buttons that will be utilized for capturing values to generate a subscription/modal checkout. My current situation involves having the radio button options visible. However, I aim to achieve a functionality wh ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Having difficulty configuring unique paths for multiple APIs using Socket.IO, ExpressJS, and Nginx

I am currently working on setting up multiple APIs on a single VPS and serving them through Nginx. My goal is to have all of them organized in separate sub-locations, as shown in the example below: For Express remote paths: [myhost].com/apps/app1/api [myh ...

Navigating the world of Rails 3 and Ajax can be a

I am having trouble grasping Ajax in Rails. I followed a tutorial a while back and got it to work with no issue. However, things get complicated when dealing with multiple models. For instance, if I have a "cats" model, implementing Ajax using the tutoria ...

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

Enhance user experience by implementing an interactive feature that displays

I have a form for adding recipes, where there is an ingredients button. Each recipe can have multiple ingredients. When the button is clicked, an input field for adding ingredients should appear below the ingredient button. What I've attempted so far ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Discovering identical elements within a list in Python through index-based location scanning

Check out this JavaScript code that can determine whether there are any duplicate elements in an array. function findDuplicates(arr) { let seen = []; for (let i = 0; i < arr.length; i++) { if(seen[arr[i]] === 1) { ...

Tips for avoiding special characters when utilizing Jquery serialization?

I'm facing an issue with my form page where I need to perform some AJAX actions before submitting. The problem arises from the fact that the form input names contain period characters, which are causing conflicts in the AJAX functionality. Unfortunate ...

Access and retrieve pkpass files from a server using React

I've exhausted all options but still can't get it to work. I'm attempting to create an Apple wallet pass using https://github.com/walletpass/pass-js. When I download the pass on the node server where I've implemented it, everything work ...

Working with Javascript: Navigating a dynamic array of elements

I need to reorganize a form on my webpage. Currently, all the fields are in one table and I want to move them around based on certain conditions. However, when I try to loop through the elements and move them, the javascript array is changing and causing m ...

Modifying the state object in ReactJS: A step-by-step guide on updating values

Below my query and explanation, you will find all the code. I am currently attempting to update the state in a grandparent class. This is necessary due to file-related reasons, and I am using Material-UI for text boxes. Additionally, I am implementing Red ...

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Tips for resolving an issue with an overflowing Uber React-Vis multicolor bar chart

I am trying to create a multi-colored bar chart using Uber's react-vis library. However, I am encountering an issue where the leftmost bar of the chart is overflowing below the YAxis instead of remaining contained to the right of it. You can view the ...

Bring in a 3-dimensional model using JSONLoader in three.js

I'm facing some challenges with incorporating a simple 3D object created in Maya into my Three.js project using JSONLoader. The object consists of various materials (Lambert and Phong) and different colors. I used Maya to create a .obj file, then Ble ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...