1

I pass array of items from JS to spring controller. I have this model in JS:

function Row() {
            this.id = 0;
            this.rulingValue = '';
            this.rulingType = '';
            this.dateStart = '';
            this.dateEnd = '';
        }

I have array of Rows - var jsonData = [];

Then I fill this array. And set to

var oMyForm = new FormData();
oMyForm.append("items", jsonData);

In Spring controller I expect this array like List<Item>

@Data
public class Item {
    private String id;
    private String rulingValue;
    private String rulingType;
    private String dateStart;
    private String dateEnd;
}

@RequestParam("items") List<Item> items

But my items parameter arrive as String. How can I get this array like List<Item>?

Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60
user5620472
  • 2,722
  • 8
  • 44
  • 97

1 Answers1

0

Springs preferred way to send JSON to a Controller is as body payload rather than as form parameter. To do so, you just have to do three things:

  1. Make sure you have a JSON library in the classpath, e.g. fasterxml.jackson.
  2. Ensure your JSON payload is sent via POST request with HTTP Content-Type "application/json"
  3. Annotate the receiving parameter in your Controller handler method with @RequestBody, e.g.

    getItems(@RequestBody List items)

A complete example can be found here: http://www.beabetterdeveloper.com/2013/07/spring-mvc-requestbody-and-responsebody.html

If you stay with sending your data as form parameter, you will have to write a custom property editor along the lines indicated here: JSON parameter in spring MVC controller. It is much harder and requires extra code.

Community
  • 1
  • 1
Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60