简体   繁体   中英

400 (Bad Request) on passing JSON to Spring controller

I am trying to pass array of objects as JSON string to the Spring controller. My data in JSON format looks like

[{
    "id": 123456,
    "name": "First Item"
},
{
    "id": 78910,
    "name": "Second Item"
}]

So I am sending to controller

@RequestMapping(value = "/some/url", method = RequestMethod.POST, consumes = "application/json")
public void doSomething(@RequestBody List<CustInfo> myCustInfoList) {
    System.out.println("Message Received " + myCustInfoList);
}

with this AJAX call

$.ajax({
  type: 'POST',
  url: '/some/url',
  contentType: 'application/json',
  data: '[{"id": 123456, "name": "First Item"}, {"id": 78910, "name": "Second Item"}]',
  success: function () {
            consloe.log("Success");
           }
});

For this I have two beans OuterCover and CustInfo . Where OuterCover has list of CustInfo and CustInfo has id and name .

public class OuterCover {

  List<CustInfo> myCustInfoList;

  //getter & setter

}

But I am getting 400 (Bad Request) on this. Any suggestion?

You need to enclose OuterCover class into other class as the request has OuterCover element. Eg

class RequestDto{

    @JsonElement("outerCover")
    private OuterCover outerCover;

    //getters and setters
}

Alternatively, you can modify the request payload and remove 'outerCover' element eg:

[{
    "id": 123456,
    "name": "First Item"
},
{
    "id": 78910,
    "name": "Second Item"
}]

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