我有一个Map<String, List<Object>>
,我想把它转换成JSON
。
这是我的:
- 第一点:**声明变量
var map = new Map(), //map
jsonObject= {}, // oject that needs to be converted to JSON
value1 = { topic: "someText1", status: "0", action: "1", comment: "someComment1" }, // values of Map
value2 = { topic: "someText2", status: "0", action: "0", comment: "someComment2" },
value3 = { topic: "someText3", status: "1", action: "1", comment: "someComment3" };
- 第二点:**函数填充多值Map
function populateMap(map, k, v) {
map[k] = map[k] || [];
map[k].push(v);
}
- 第三点:**填充Map
- //map的key是web页面中各种属性的拼接,用分隔|*
populateMap(map, 'release|attachment|license1', value1);
populateMap(map, 'release|attachment|license1', value2);
populateMap(map, 'release1|attachment1|license1', value1);
populateMap(map, 'release1|attachment1|license2', value2);
populateMap(map, 'release1|attachment1|license3', value3);
populateMap(map, 'release2|attachment2|license2', value1);
populateMap(map, 'release2|attachment2|license2', value2);
- 第四点:**迭代map并填充jsonObject
for (var i in map) {
var keys = i.split('|'), // splitting keys based on |
last = keys.pop(),
values = map[i];
values.forEach(function (item, index) {
keys.reduce((r, a) => r[a] = r[a] || {}, jsonObject)[last] = item;
});
}
- 第五点:**当前输出(jsonObject打印在控制台上)
{
"release": {
"attachment": {
"license1": "[Object]"
}
},
"release1": {
"attachment1": {
"license1": "[Object]",
"license2": "[Object]",
"license3": "[Object]"
}
},
"release2": {
"attachment2": {
"license2": "[Object]"
}
}
}
- 第6点:**预期输出(jsonObject)
{
"release": {
"attachment": {
"license1": "[Object, Object]" // expecting array of objects here ^^
}
},
"release1": {
"attachment1": {
"license1": "[Object]",
"license2": "[Object]",
"license3": "[Object]"
}
},
"release2": {
"attachment2": {
"license2": "[Object, Object]"
}
}
}
^^因为map有对象数组,所以我想有对象数组在jsonObject
。
有人可以帮助我调整需要在Point 4的map
遍历中做的调整来获得预期的结果吗?
2条答案
按热度按时间r8xiu3jd1#
您可以使用
.set
、.get
、.has
和.delete
等方法与Map
交互;将其元素设置为属性不正确。然后遍历map看起来像这样:
setPath
实现基本保持不变:总人数:
camsedfj2#
可以使用对象Map器将多值Map解析为对象或JSON
new ObjectMapper.writeValueAsString(requestValue.toSingleValueMap())