【问题标题】:Java class receives Ajax JSON post as nullJava 类接收 Ajax JSON 帖子为 null
【发布时间】:2019-12-22 06:54:30
【问题描述】:

我正在尝试使用 ajax post 方法将 json 数据发送到 Java 类。当我硬编码一个 json 字符串时,我的 Java 对象接收它就好了,但是当我尝试发送一个用 JSON.stringify() 创建的 json 字符串时,我的控制器中的所有空值......

这是流程,我在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>

以下 javascript 从该表中读取并使用 ajax 将其发送到我的控制器:

$('#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);
        }
    });
});

在 console.log(JSON.stringify(myObj)) 调用期间,以下内容会打印到控制台:

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

这是代表我正在尝试创建的对象的 Java 类:

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

最后是控制器类接收 JSON 数据并使用 toString 方法显示我们得到的内容:

@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;
}

}

在我们的 NewPartRequest newPartRequest 对象上调用 toString() 方法并打印以下内容:

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

我已经被这个问题困扰了很长时间,我无法弄清楚为什么我的所有属性都得到了 null 值。

【问题讨论】:

  • @RequestBody NewPartRequest newPartRequest
  • 嗨@muasif80,我添加了\@RequestBody 参数,但仍然遇到同样的问题。 ...
  • 删除这个produces = MediaType.APPLICATION_JSON_UTF8_VALUE
  • @RestController替换@Controller
  • 这个不需要String response = jsonify(newPartRequest);

标签: javascript java json ajax


【解决方案1】:

您需要像下面这样更改 ajax 帖子

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

或者您可以像这样更改后端代码

List&lt;NewPartRequest&gt;

然后像下面这样从 ajax 传递

data : JSON.stringify(myObj.myrows),

您实际上是在传递一个对象列表并在后端控制器方法中期望一个对象。

【讨论】:

  • 非常感谢@muasif80 !!!我想我看代码太久了,以至于我对它视而不见。非常感谢您花时间帮助我,我真的很感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 2016-05-02
  • 2019-02-10
  • 2014-08-27
相关资源
最近更新 更多