How to pass a javascript (js) Map to spring boot C

2020-03-26 08:18发布

问题:

I've a Java Script map having key value pairs which i Need to send to spring boot contoller :--

Example :--

 var myMap = new Map();
     myMap.set('1', 'value1');
     myMap.set('2', 'value2');
    

I'm not able to get this JavaScript (js) map in my spring boot controller. To my best practice I'm trying to get this map in java's HashMap or Map. A help is highly appreciated. :)

回答1:

Try below:

var myMap = {};
myMap["names"] = ["Alex"];
myMap["fruit"]  = ["Apple"];

Modify javascript code to use Ajax:

$.ajax({
     type : "POST",
     url :  "/reqURL",
     contentType: "application/json",
     data : JSON.stringify(myMap) // .....

Controller code like below:

 @RequestMapping(value = "/reqURL", method = RequestMethod.POST, consumes="application/json")
    @ResponseBody
    public List<String> reqControl(@RequestBody Map<String, List<String>> myMap) {
       // do something with parameters ...
    }


回答2:

I've figured out the solution :-

var myMap = new Map();
         myMap.set('1', 'value1');
         myMap.set('2', 'value2');
         myMap.set('3', 'value3');
         myMap.set('4', 'value4');

         //Making JS Map compatible for JSON.Stringify
         const out = Object.create(null)
         myMap.forEach((value, key) => {
          if (value instanceof Map) {
            out[key] = map_to_object(value)

          }
          else {
            out[key] = value
          }
        })

$.ajax({
     type : "POST",
     url :  "/yourURL",
     contentType: "application/json",
     data : JSON.stringify(myMap) //......

@RequestMapping(value = "/yourURL", method = RequestMethod.POST, consumes="application/json")
    @ResponseBody
    public List<String> reqControl(@RequestBody Map<String,<String> myMap) {
       //  further code.   
    }