old_dd
old_dd

Reputation: 175

Java class receives Ajax JSON post as null

I am trying to use ajax post method to send json data to a Java class. When I hardcode out a json string my Java object recieves it just fine, but when I try to send a json string created with JSON.stringify() I get all nulls in my controller...

Here is the flow, I have the following table in html:

<table class="table" id="internalUnsubmittedPartRequests">
    <thead>
        <tr>
            <th id="partID">partID</th>
            <th id="quantity">quantity</th>
            <th id="applicableModel">applicableModel</th>
            <th id="queueName">queueName</th>
            <th id="issueType">issueType</th>
            <th id="controlCode">controlCode</th>
            <th id="position">position</th>
            <th id="command">command</th>
            <th id="activationDate">activationDate</th>
            <th id="flushDate">flushDate</th>
        </tr>
    </thead>
    <tbody>
        <!-- Dynamically Generated via newRequest.js -->
    </tbody>
</table>

And the following javascript to read from that table and use ajax to send it to my controller:

$('#submit_set_btn').click(function(event) {
    var myRows = [];
    var $headers = $("th");
    var $rows = $("#internalUnsubmittedPartRequests tr").each(function(index) {
      $cells = $(this).find("td");
      myRows[index] = {};
      $cells.each(function(cellIndex) {
        myRows[index][$($headers[cellIndex]).html()] = $(this).html();
      });    
    });
    myRows.shift();
    var myObj = {};
    myObj.myrows = myRows;
    console.log(JSON.stringify(myObj));

    $.ajax({
        type : "POST",
        // contentType : "application/json; charset=utf-8",
        url : window.location,
        data : JSON.stringify(myObj),
        dataType : 'json',
        success : function(result) {
            //alert("success");
            console.log("success");
            console.log(result);
        },
        error : function(e) {
            //alert("fail");
            console.log("fail");
            console.log(e);
        }
    });
});

The following is printed to the console during the console.log(JSON.stringify(myObj)) call:

{"myrows":[{"partID":"data","quantity":"data","applicableModel":"data","queueName":"data","issueType":"data","controlCode":"data","position":"data","command":"data","activationDate":"data","flushDate":"data"}]}

Here is the Java class representing the object I am trying to create:

public class NewPartRequest
{
private String partID;
private String quantity;
private String applicableModel;
private String queueName;
private String issueType;
private String controlCode;
private String position;
private String command;
private String activationDate;
private String flushDate;

@Override
public String toString() {
    return getPartID() + " " + getQuantity() + " " + getApplicableModel() + " " + 
           getQueueName() + " " + getIssueType() + " " + getCommand() + " " + 
           getActivationDate() + " " + getFlushDate();
}


//Getters and Setters below this line

And finally the controller class receiving the JSON data and using the toString method to display what we got:

@Controller
public class DistributionNewRequestController {

@RequestMapping(value = "/distribution/internal/unsubmitted/new-request", method = { RequestMethod.GET })
public String newRequest() {
    return "new-request";
}

@RequestMapping(value = "/distribution/internal/unsubmitted/new-request", method = {
        RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public @ResponseBody String internalRequestPost(@RequestBody NewPartRequest newPartRequest) {

    System.out.println("The new part request toString method: ");
    System.out.println(newPartRequest.toString());

    String response = jsonify(newPartRequest);
    return response;

}

private String jsonify(NewPartRequest in) {
    Gson gson = new Gson();
    String out = gson.toJson(in);
    return out;
}

}

The toString() method gets called on our NewPartRequest newPartRequest object and the following is printed:

The new part request toString method: 
null null null null null null null null

I have been stuck on this issue for a long time now, I can't figure out why I am getting the value null for all of my attributes.

Upvotes: 0

Views: 368

Answers (1)

muasif80
muasif80

Reputation: 6006

You need to change the ajax post like below

data : JSON.stringify(myObj.myrows[0]),

or you can change in the backend code like this

List<NewPartRequest>

and then pass from ajax like below

data : JSON.stringify(myObj.myrows),

You were actually passing a list of objects and expecting a single object in the backend controller method.

Upvotes: 1

Related Questions