简体   繁体   English

如何将嵌套的 JSON 传递给 Spring Controller

[英]How to pass nested JSON to Spring Controller

I have my JSON in following format:我的 JSON 格式如下:

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

From my Jquery code i am passing the AJAX call as:从我的 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);
            }
   });

This code runs fine when the json is not nested and has value as:当 json 未嵌套且具有以下值时,此代码运行良好:

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

the values are getting printed in controller, but when the JSON is in following format, i see null for these values:这些值正在控制器中打印,但是当 JSON 采用以下格式时,我看到这些值为 null:

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

Please advise请指教

The controller code:控制器代码:

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

Probably your OrgVODummy class looks like below:可能您的OrgVODummy类如下所示:

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

But you should have something like that:但是你应该有这样的东西:

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

Than in your controller change to this:比在您的控制器中更改为:

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

And this should work with this json ( organization starts with lower letter):这应该适用于这个 json( organization以小写字母开头):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM