Joao Evangelista
Joao Evangelista

Reputation: 2465

Error 400 Spring JSON @RequestBody

I'm facing an error 400 when trying to post data to Spring Controller using @RequestBody

My Ajax method:

 $(document).on('click', 'a[href|=#undo]', function () {

        var i = $(this).attr('data-ref');
        var uri = '/catalog/uso/undo/' + i;

        var data = {"quantidade":$('.qntundo').val()};

        console.log(JSON.stringify(data));

        $.ajax({
            url: uri,
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            headers: {
                "Content-Type": "application/json"
            },
            async: false,
    ......

data produces this : {"quantidade":"1"}

and my method is like :

   @RequestMapping(value = "/catalog/uso/undo/{id}",
                method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public
        @ResponseBody
        String undo(@PathVariable("id") int id,
                    @RequestBody Integer qnt) {
   //some logic here
}

What I'm doing wrong, is that I cant use Integer as "body"? Or I need tell to @RequestBody look for "quantidade", if is that how can I do this?

PS: I have Jackson lib on my pom.xml also have

<mvc:annotation-driven/>
    <mvc:default-servlet-handler/>

enabled in my Spring XML

Upvotes: 0

Views: 2918

Answers (1)

Joao Evangelista
Joao Evangelista

Reputation: 2465

I worked around with the tips in comments the result is I changed the type of annoted field on method making that:

@RequestMapping(value = "/catalog/uso/undo/{id}",
            method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public
    @ResponseBody
    String undo(@PathVariable("id") int id,
                @RequestBody LinkedHashMap qnt) {

Now I have a LinkedHashMap comming and I can access it to get the value, like:

Object o = qnt.get("qnt");

where .get("your json object name here");

I was needing an Integer so I did a conversion:

int quantidade = Integer.valueOf(String.valueOf(o));

Now I have access to value of json within the variable quantidade

Upvotes: 0

Related Questions