'How to pass a javascript (js) Map to spring boot Controller?

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. :)



Solution 1:[1]

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.   
    }

Solution 2:[2]

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 ...
    }

Solution 3:[3]

In my case I pass the map to a servlet but maybe it can help someone:


    $.ajax({
    ...
    data: { 
     "MY_MAP": JSON.stringify(Object.fromEntries(myMap))
    },
    ...

String myMapString = parameters.get("MY_MAP");
Map<String, String> myMap = new Gson().fromJson(myMapString, new TypeToken<HashMap<String, String>>() {}.getType());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sumit
Solution 2 Amit K Bist
Solution 3 elenamf86