简体   繁体   中英

How to pass nested JSON to Spring Controller

I have my JSON in following format:

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

From my Jquery code i am passing the AJAX call as:

    $.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:

{"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:

{"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:

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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