问题描述
我的REST控制器期望输入以下格式的请求,并将其成功转换为包含Map和String作为参数的Java对象:
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"
}
我正在从html表单获取数据,如下所示:
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");
这将导致包含{key1 => value1,key2 => value2等}和一个String的映射.我一直试图像这样将其转换为json字符串,但是它似乎不起作用:
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);
但是,我最终得到以下字符串:`{"myMap":{},"String":"myString"}''.因此,我可能需要做一些不同的事情来对地图进行字符串化,但是我尝试的任何方法都没有用.
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.
有人可以帮我吗?
推荐答案
您可以编写一个简短的转换函数,以使映射成为可以被字符串化的对象.
You can write a short conversion function to make a map into an object that can be stringified.
console.clear()
function mapToObj(map){
const obj = {}
for (let [k,v] of map)
obj[k] = v
return obj
}
const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");
const myString = "string value"
const myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
const json = JSON.stringify(myJson);
console.log(json)
这里是一个可以在Map存在但其他ES6构造不起作用的版本中运行的版本(尽管这似乎是编辑器设置问题).
Here is a version that that presumably would work where Map exists but some other ES6 constructs do not (though, this seems like an editor settings issue).
console.clear()
function mapToObj(map){
var obj = {}
map.forEach(function(v, k){
obj[k] = v
})
return obj
}
var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");
var myString = "string value"
var myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
var json = JSON.stringify(myJson);
console.log(json)
这篇关于从JS Map和String创建JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!