【问题标题】:How to pass nested JSON to Spring Controller如何将嵌套的 JSON 传递给 Spring Controller
【发布时间】:2020-02-18 20:40:01
【问题描述】:

我的 JSON 格式如下:

    "Organization":{
             "legalname" : "",
              "dba" : "",
              "fein" : ""
        }           

从我的 Jquery 代码中,我将 AJAX 调用传递为:

    $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "OMS/ConfirmationR",
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (JSONText) {
               alert('success');
               console.log("SUCCESS: ", data);
            },
            error: function(xhr, status, error){
                var errorMessage = xhr.status + ': ' + xhr.statusText
                alert('Error - ' + errorMessage);
            }
   });

当 json 没有嵌套并且具有以下值时,此代码运行良好:

{"legalname":"test","dba":"dba","fein":"123"},

值正在控制器中打印, 但是当 JSON 采用以下格式时,我看到这些值为 null:

{"Organization":{"legalname":"test","dba":"dba","fein":"123"}}

请指教

控制器代码:

@RequestMapping("OMS/ConfirmationR")
public ResponseEntity<?> goToOrgConfReg(@RequestBody OrgVODummy org, Model model) {
    System.out.println("In goToOrgConfReg!!! getLegalName : " + org.getLegalname() + " DBA: " + org.getDba()
            + " FEIN:" + org.getFein());
    AjaxResponse result = new AjaxResponse();
    if (org.getLegalname() == null) {
        System.out.println("@RequestBody is null");
        result.setMsg(" Failed");
    } else {
        System.out.println("@RequestBody is not null");
        result.setMsg(" Pass");
    }

    return ResponseEntity.ok(result);
}

【问题讨论】:

  • OrgVODummy类的定义是什么?

标签: jquery json ajax spring controller


【解决方案1】:

您的OrgVODummy 课程可能如下所示:

class OrgVODummy {
  private String legalname;
  private String dba;
  private String fein;
// getters and setters
}

但你应该有类似的东西:

class OrganizationDummy {
  private OrgVODummy organization;
// getters and setters
}

比你的控制器改成这样:

public ResponseEntity<?> goToOrgConfReg(@RequestBody OrganizationDummy org, Model model) {

这应该适用于这个 json(organization 以小写字母开头):

{"organization":{"legalname":"test","dba":"dba","fein":"123"}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2016-10-29
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2015-07-10
    相关资源
    最近更新 更多