Passing json as body and another object as parameter to spring controller

I’m passing back a list of objects as json to my spring controller, but I also need to pass it some customer details too such as firstname, lastname, address, payment type – so I thought I create a POJO for this and pass this as a request param but no luck.

Spring controller:

  @RequestMapping(value = "/addstock", method = RequestMethod.POST)
    public @ResponseBody
    String addPersons(@RequestBody StockList stock, @RequestParam(name="details") AddDetails details) throws ParseException, IOException

Pojo is AddDetails which has the getter/setter etc using lombok. I try to pass as follows in my javascript:

 function sendData() {
            var stocks = JSON.stringify({'stocks': model.stock()});
            var obj = { "firstname":"Steve", "lastname":"Green"};
            obj = JSON.stringify({'details':obj});
                type: 'POST',
                data:  stocks,
                dataType: "html",
                contentType: 'application/json',
                mimeType: 'application/json',
                success: function(data){
                    return false;

But obviously I cannot pass an object across to the details param. Is it possible another way?

Many thanks

27 thoughts on “Passing json as body and another object as parameter to spring controller”

  1. There are several ways to do this. The first option is to remove the @RequestParam annotation and Spring will automatically bind the parameters in the query string to your POJO. However, in your code you are appending a JSON representation to the URL, and that’s not possible. This is the correct syntax you should be using for the AddDetails fields:


    Another possible solution is to define a DTO that contains both the list of stocks and an AddDetails object and pass it as body of the request. For example:

    public class StockListDTO{
        List<Stock> stocks;
        AddDetails details;
        //Getter and setters or use Lombok

    And your method signature:

     @RequestMapping(value = "/addstock", method = RequestMethod.POST)
        public @ResponseBody
        String addPersons(@RequestBody StockListDTO body) throws ParseException, IOException

Leave a Comment