My REST controller expects request input of the following format, which it successfully converts to a Java object containing a Map and a String as parameters:
{
"myMap" : {
"key1": "value1",
"key2": "value2",
"key3": "value3"},
"myString": "string value"
}
I am getting my data from an html form like so:
var myMap = new Map();
var String = document.getElementById('String').value;
for (var i = 0 ; i<anArray.length ; i++){
var input = document.getElementsByClassName('input_' + (i+1));
for (var j = 0 ; j<3 ; j++){
if (input[j].checked){
myMap.set(input[j].name, input[j].id);
}
}
}
Basically, this code boils down to:
var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");
This results in a map containing {key1 => value1, key2 => value2, etc} and a String. I have been trying to turn this into a json string like so, but it doesn't seem to work:
var myJson = {};
myJson.myMap = myMap;
myJson.myString = myString;
var json = JSON.stringify(myJson);
However, I am ending up with the following string: `{"myMap":{},"String":"myString"}' . So I probably have to do something different to stringify a map, but nothing I try is working.
Can anyone help me out?
var obj = new Object(); obj.name = "Raj"; obj. age = 32; obj. married = false; var jsonString= JSON. stringify(obj);
We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple.
The toJSON() method returns a date object as a string, formatted as a JSON date. JSON dates have the same format as the ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ.
Using ES6 syntax, and especially if you have nested maps (otherwise Idan Dagan's answer is simpler), you can use the JSON.stringify()'s second argument, the reducer, as follows:
JSON.stringify(myMap, (key, value) => (value instanceof Map ? [...value] : value));
This hack will do the job (but it's a global override and must be used carefully):
Map.prototype.toString = function() {
let result = {};
this.forEach((key, value) => { result[key] = value;});
return JSON.stringify(result);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With