0

I made a ajax post call in the front end.

let data = {
        marketplaceId: "1",
        monetaryAmount: {
            amount: 100,
            currencyCode: "USD",
        }, 
    }

    $.post(posturl, data, function(returnedData) {
            console.log(returnedData)
        }
       ).fail(function() {
           console.log("error")
       })

In my spring mvc controller, I want to map monetaryAmount json object to A java object SimpleAmount.

SimpleAmount.java

public class SimpleAmount {
    private BigDecimal amount;
    private String currencyCode;


  public BigDecimal getAmount() {
    return this.amount;
  }

  public void setAmount(BigDecimal amount) {
    this.amount = amount;
  }


  public String getCurrencyCode() {
    return this.currencyCode;
  }

  public void setCurrencyCode(String currencyCode) {
    this.currencyCode = currencyCode;
  }
}

Controller.java

@RestController
public class Controller {

    @RequestMapping(value = "/rpl/updateasinlimit", method = RequestMethod.POST)
    @ResponseBody
    public BGCServiceResponseStatus updateAsinLimit(
            @RequestParam Long marketplaceId,
            @RequestParam @RequestBody SimpleAmount monetaryAmount) {

        ......
    }
}

However, SimpleAmount monetaryAmount never gets mapped properly. It seems to me that all those primitive type will get mapped easily, but not java object

But I dont know how I can map json object sent from ajax post to the parameter passed into spring controller?

齐天大圣
  • 1,169
  • 5
  • 15
  • 36

1 Answers1

0

Your request body is application/x-www-form-urlencoded(not json) and looks like:

marketplaceId=1&monetaryAmount%5Bamount%5D=100&monetaryAmount%5BcurrencyCode%5D=USD

Problem 1 is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation. More info


Problem 2 Spring actually has hard time understanding the percent encoding format ( %5D and %5B) for some reason.


Here is how you can solve this: Post1, Post2.

One more option is to create response POJO

public class SomeResponse {
    private long marketplaceId;
    private SimpleAmount monetaryAmount;

}

Change you js code to actually send json instead of application/x-www-form-urlencoded

$.ajax({
    type: 'POST',
    url: "/rpl/updateasinlimit",
    data: JSON.stringify(data),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

And then you can use it like this in controller:

public String updateAsinLimit(
        @RequestBody SomeResponse pojo) {
        System.out.println(pojo.getMarketplaceId());
        System.out.println(pojo.getMonetaryAmount());

        // ...
}
varren
  • 14,551
  • 2
  • 41
  • 72